0

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.

caseA caseB

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???

cmii
  • 3,556
  • 8
  • 38
  • 69
  • Show us your constraints. You should not need to update any constraint in code to get the result you want to, if they're correctly set up (with compression and hugging priorities correctly set). – jcaron Dec 08 '15 at 17:25
  • Is there any special case you are using an UITextView instead of an UILabel? – DevAndArtist Dec 08 '15 at 20:07
  • Yes, because I need to use exclusionPaths on the textContainer, around the back button. – cmii Dec 08 '15 at 20:09
  • Possible duplicate of [How to adjust the height of a textview to his content in SWIFT?](http://stackoverflow.com/questions/29431968/how-to-adjust-the-height-of-a-textview-to-his-content-in-swift) – Tomte Nov 17 '16 at 19:04

1 Answers1

0

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 
    }
}
DevAndArtist
  • 4,971
  • 1
  • 23
  • 48