Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-activating NSLayoutConstraint finds nil while unwrapping optional

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?

like image 858
Wiingaard Avatar asked May 23 '16 11:05

Wiingaard


1 Answers

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.

like image 113
Iulian Onofrei Avatar answered Sep 22 '22 12:09

Iulian Onofrei