I want to set the height of my UITextView
programmatically to fit the contents accordingly. I've set the UITextView
's default height to follow layout constraints I've set, but wish to change it when the user touches a button.
@IBOutlet weak var descriptionHeight: NSLayoutConstraint!
I've tried to use layoutIfNeeded()
, but it doesn't change the size of my text view (as the size is kept by the layout constraint).
I've tried to temporarily disable the constraints like so:
print("before: \(descriptionTextView.frame)")
descriptionHeight.active = false
descriptionTextView.layoutIfNeeded()
print("after: \(descriptionTextView.frame)")
descriptionHeight.constant = descriptionTextView.frame.height
descriptionHeight.active = true
But when when accessing the outlet after deactivating it, it throws an exception:
fatal error: unexpectedly found nil while unwrapping an Optional value
It seems that it is calculating the size properly though:
before: (8.0, 8.0, 398.0, 100.0)
after: (8.0, 8.0, 398.0, 954.666666666667)
Why does this happen?
Is there a better way of calculating and setting the proper size of my UITextView
?
Make the outlet strong
:
@IBOutlet strong var descriptionHeight: NSLayoutConstraint!
Edit:
It seems like the latest version of Xcode adds the outlets as:
@IBOutlet var descriptionHeight: NSLayoutConstraint!
as @Dan mentioned in the comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With