KennethTsang / GrowingTextView

An UITextView in Swift. Support auto growing, placeholder and length limit.
MIT License
1.07k stars 133 forks source link

Dynamic Text View - Lines of text shifting up #23

Closed jboo1212 closed 6 years ago

jboo1212 commented 6 years ago

I have some sample code below where I try to mimic the dynamic text view calculation like your code. My question is how is the top inset addressed with respect to the text container? When I get to about the second line, my first line shifts up pretty much to very edge of the top frame of Text View. I want the text to stay center to the line height.

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textView.delegate = self
        self.textView.backgroundColor = .lightGray
    }

    func textViewDidChange(_ textView: UITextView) {
        self.calculateSize()
    }

    func calculateSize() {
        let fixedWidth = textView.frame.size.width
        textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
        let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
        var newFrame = textView.frame
        newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
        textView.frame = newFrame
    }
}
KennethTsang commented 6 years ago

Try to call textview.scrollRangeToVisible(NSMakeRange(-1, 0)) after height changing.

jboo1212 commented 6 years ago

Wow this does the trick! Is location = -1 defined by the text?

KennethTsang commented 6 years ago

The "-1" location seems not documented, but a little trick to scroll to bottom.