如何在代码中更改帧后更新约束

时间:2014-07-24 11:58:00

标签: ios objective-c xcode autolayout nslayoutconstraint

我有两个按钮,在两个自动布局都启用但在运行时我需要更改它们的框架。我改变但对他们没有影响我通过调用此constraintWithItem方法和 [self.btnDeviceContacts updateConstraints]; [self.btnFacebookContacts updateConstraints]; 多次尝试 还[self.view setNeedsDisplay]; [self.view layoutSubviews];

通过调用此constraintWithItem仅效果第一个按钮

,它不会对此产生影响
    NSLayoutConstraint *constrain1 = [NSLayoutConstraint
                                 constraintWithItem:self.btnDeviceContacts
                                 attribute:NSLayoutAttributeWidth
                                 relatedBy:NSLayoutRelationEqual
                                 toItem:nil
                                 attribute:NSLayoutAttributeNotAnAttribute
                                 multiplier:1
                                 constant:160];

 [self.view addConstraint:constrain2];
NSLayoutConstraint *constrain2 = [NSLayoutConstraint
                                  constraintWithItem:self.btnFacebookContacts
                                  attribute:NSLayoutAttributeWidth
                                  relatedBy:NSLayoutRelationEqual
                                  toItem:nil
                                  attribute:NSLayoutAttributeNotAnAttribute
                                  multiplier:1
                                  constant:160];
NSArray * array = [[NSArray alloc] initWithObjects:constrain1,constrain2, nil];
[self.view addConstraints:array];

故事板上按钮的初始框架

[self.btnDeviceContacts setFrame:CGRectMake(0, 60, 106, self.btnDeviceContacts.frame.size.height)];
     [self.btnFacebookContacts setFrame:CGRectMake(107, 60, 106, self.btnFacebookContacts.frame.size.height)];

在代码中更改了Button的框架:

[self.btnDeviceContacts setFrame:CGRectMake(0, 60, 160, self.btnDeviceContacts.frame.size.height)];
     [self.btnFacebookContacts setFrame:CGRectMake(161, 60, 160, self.btnFacebookContacts.frame.size.height)];

请帮助我,如何更新约束或如何解决此问题。提前谢谢。

1 个答案:

答案 0 :(得分:0)

尝试[self.view updateConstraints]也请在updateContraints

之前尝试[self.view layoutIfNeeded]

编辑:使用常量属性

 @property (nonatomic) NSLayoutConstraint * leftSideButtonContact;

只是

leftSideButtonContact.constant = 20;  // your change in property will effect the layout directly

确保在.xib文件中应用约束