I have a UITableViewCell which has two UITextFields (without borders). The following constraints are used to set up the horizontal layout.
@\"|-10-[leftTextFi
I had a similar requirement with a UITextView (had to dynamically increase it's height and some other things).
What I did was something similar to this:
Considering self.contentView is the superview of textField
- (IBAction)textFieldDidChange:(UITextField *)textField {
//You can also use "textField.superview" instead of "self.contentView"
[self.contentView setNeedsUpdateConstraints];
//Since you wish to animate that expansion right away...
[UIView animateWithDuration:0.1 animations:^{
[self.contentView updateConstraintsIfNeeded];
}];
NSLog(@"%@", NSStringFromCGSize(textField.intrinsicContentSize));
}
Also, considering the requirements I had, I had to override the updateConstraints method of my UITextView's superview.
Should you choose to opt for that solution (maybe for a more fine tuned approach), you can do:
- (void)updateConstraints {
[super updateConstraints];
//Firstly, remove the width constraint from the textField.
[self.myTextField removeConstraint:self.textFieldWidthConstraint];
self.textFieldWidthConstraint = nil;
CGSize contentSize = self.myTextField.intrinsicContentSize;
self.textFieldWidthConstraint = [NSLayoutConstraint constraintWithItem:self.myTextField attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:contentSize.width];
[self.myTextField addConstraint:self.textFieldWidthConstraint];
}
As mentioned, the override option was used by me because I required a more fine tuned approach.
Additionally, as always you'll need to make sure that you're checking for any edge cases (in terms of sizing values) that you think you might encounter.
Hope this helps!
Cheers!