Update view's frame keeping constraints

时间:2015-10-29 11:08:20

标签: ios objective-c autolayout constraints

Simply put, look at the pictures below:

  1. I design a view, put the constraint to top left right bottom. It work correctly when change view orientation.

Base

  1. Put a simple code to change the view height:

    // CODE

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
       self.view.translatesAutoresizingMaskIntoConstraints = NO;
    
       CGRect updateViewFrame = self.updatingView.frame;
       updateViewFrame.size.height = textField.text.floatValue;
       self.updatingView.frame = updateViewFrame;
    
       [self.view setNeedsLayout];
    
       return YES;
     }
    

??? Why there's a mess with the code format in SO?

Result

What should I do in the code to make the UITextfield move up, along with the view's height, without changing the textField's frame directly?? My autolayout constraints doesn't work any longer after I change the view's frame.

Other notes: 1. The containerView is a scrollView, so no worry about the long height. 2. I ask if there's a way to work without directly change the UITextField's frame, because I'll add many more views, controls later. It may cause a mess if I have to update the frame for every single control there will be :(

1 个答案:

答案 0 :(得分:1)

如果要在Interface Builder中创建自动布局约束,可以为它们创建IBOutlets,方法与视图,按钮等相同。您可以更改此约束的常量和动画/刷新观点:

@interface ViewController ()

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;

@end

@implementation ViewController

- (void)someMethod {

    self.topSpace.constant = 60;

    [UIView animateWithDuration:1 animations:^{
        [self.view layoutSubviews]; //just this line if you don't want the animation
    }];

}

@end

手动设置框架会破坏与该视图关联的所有约束。