Resize UIView to wrap it's contents with auto layout turned off

2.2k Views Asked by At

Hey so i have a UITextView inside a UIView which i dynamically load with content. I'm resizing the height of the text view using this solution

I have auto layout turned off for this to work (other solutions like sizeToFit() were not working with auto layout ON) but when i do this, even though all the content of the text view does get rendered, it overflows the bounds of it's containing UIView.

I tried to use the same solution that worked for the text view on it's container too, but that didn't do anything.

One thing that DOES seem to work is:

newFrame = containerView.frame
newFrame.size.height = textView.frame.size.height
containerView.frame = newFrame

But this isn't what i need coz i'll also have a couple of labels in this container view so it's height can't be the same as the text field's.

Is there a way to fix this without turning auto layout on again? (Will turning auto layout on even help?) And if turning auto layout on will fix this, then is there a way to keep the dynamic size of the text view (coz turning it on will break that)?

I'm very new to this. Appreciate the help.

Oh and i'm actually developing a tvOS application, not an iOS one. Dunno if that makes a difference.

EDIT:

Here's the actual code:

@IBOutlet weak var container: UIView!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var text: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    print(text.frame.origin.x, text.frame.origin.y)

    text.scrollEnabled = false

    text.text = "bla blah blah blah boo boo boo boooooo boo blah yo yo yo yo yo hello"
    let fixedWidth = text.frame.size.width
    let newSize = text.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
    var newFrame = text.frame
    newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
    text.frame = newFrame
}

This dynamically expands the text view when the content changes. Adding:

newFrame = containerView.frame
newFrame.size.height = textView.frame.size.height
containerView.frame = newFrame

resizes the container UIView, but makes the text.frame.origin.y of the text view 0. So adding any other elements to the container just overlaps with the text view.

1

There are 1 best solutions below

4
On

You can achieve this with both autolayout or framing. If you are using frame then you need to take into consideration the height of all other components in the containerView. Lets say you have 3 Labels, 1 above the textview and 2 below it having 15 points has vertical distance between each, then your containerView height should be:

newFrame = containerView.frame
newFrame.size.height = 15 + label1.frame.size.height + 15 + textView.frame.size.height + 15 + label2.frame.size.height + 15 + lable3.frame.size.height + 15
containerView.frame = newFrame

With Autolayout you have to set proper vertical constraint among the components to resize accordingly.