Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change height constraint programmatically

I want to change the height constraint of a UITextView programmatically so I set the constraint as an outlet in my controller like this:

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *descriptionHeightConstraint; 

To change it I do the following:

self.descriptionHeightConstraint.constant = self.description.contentSize.height; 

This works if I do it in viewDidAppear but the problem with this is that I can see how the height changes after the view displayed which is not very user friendly so I tried doing it in viewWillAppear but didn't work there, the height doesn't change. Calling setNeedsUpdateConstraints after changing the constraint didn't work either.

Why is working in viewDidAppear and not in viewWillAppear? Any workaround?

Thanks in advance!

like image 748
mxch Avatar asked Jan 05 '14 04:01

mxch


People also ask

How do I change a constraint in Swift?

Select the height constraint from the Interface builder and take an outlet of it. So, when you want to change the height of the view you can use the below code. Method updateConstraints() is an instance method of UIView . It is helpful when you are setting the constraints programmatically.

How do I set constraints programmatically in Objective C?

NSLayoutConstraint *centreHorizontallyConstraint = [NSLayoutConstraint constraintWithItem:self. uiButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self. view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]; [self. view addConstraint:centreHorizontallyConstraint];

How do I give a constraint to button programmatically in Swift?

Add the button in the view, give it constraints and as you are using constraints, you can skip the button. frame and add widthAnchor and heightAnchor . At last activate them and keep translatesAutoresizingMaskIntoConstraints as false . Also, it will be better if you can add proper names.


1 Answers

Try setting the constant in viewDidLayoutSubviews instead.

Note that using the text view's contentSize property to set the text view's height does not work in iOS 7. See https://stackoverflow.com/a/18837714/1239263

like image 155
bilobatum Avatar answered Nov 07 '22 05:11

bilobatum