简体   繁体   中英

Size of UITextView after setting its height depending of its content SWIFT

I have a UITextView, with a height constraint in order to adapt the height of the frame to its content (depending of the length of the string). (I use autolayout). It works fine.

案例A 案例B

But, I don't understand something about the size of the textview frame.

I explain.

I display the frame infos after setting the text of the uitextview, and after updating the constraint.

override func viewDidLoad() {
    ...
    self.textview.text = post.title
    ...
}

override func viewDidLayoutSubviews() {

    let contentSize = self.textview.sizeThatFits(self.textview.bounds.size)
    self.heightConstraint.constant = contentSize.height
    self.textview.layoutIfNeeded()

    print(self.textview.frame) // frame
    print(self.textview.bounds) // bounds
}    

The result:

For case A:

(8.0, 0.0, 584.0, 97.0) //frame
(0.0, 0.0, 584.0, 97.0) //bounds

For case B:

(8.0, 0.0, 584.0, 97.0) //frame
(0.0, 0.0, 584.0, 97.0) //bounds

I don't understand why the height of the frame is the same in both case???

This will solve the problem if you don't need the scrolling part of the UITextView :

class ViewController: UIViewController {

    let textView = UITextView()

    override func viewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()

        self.view.addSubview(self.textView)
        self.textView.backgroundColor = UIColor.redColor()
        self.textView.text = "Hello world Hello world Hello world Hello world Hello world Hello world"

        self.textView.translatesAutoresizingMaskIntoConstraints = false
        self.textView.topAnchor.constraintEqualToAnchor(self.view.topAnchor).active = true
        self.textView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor).active = true
        self.textView.rightAnchor.constraintEqualToAnchor(self.view.rightAnchor).active = true

        self.textView.scrollEnabled = false // magic which will help auto expanding 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM