Search code examples
iosswiftautolayoutswift4

dynamic Auto Layout resize


I have a container with a UITextView inside it. The container is supposed to resize according to the height of the text view. I'm currently using there lines to make it work

 let fixedWidth = textView.frame.size.width
    let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    let textViewHeight = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

    containerView.frame.size = textViewHeight

The thing is, i'm using Auto Layout on the rest of the constraints and I would like to manage this as an Auto Layout as well. I've tried using .greatestFiniteMagnitude in my auto layout but that didn't do much for me.


Solution

  • Here is the layout and constraints to allow the text field to auto-size and auto-expand its containing view.

    The containerView (blue) is constrained Top/Leading/Trailing, but not Bottom or Height.

    The textView is constrained Top/Leading/Trailing/Bottom, all at 8, and Scrolling is Disabled.

    Small amount of text: enter image description here

    Longer amount of text: enter image description here

    At run-time, when you set the text -- or when typing in the field -- its Height will auto-size based on the amount of text.