【问题标题】:How to update Constraint after change frames in code如何在代码中更改帧后更新约束
【发布时间】:2014-07-24 11:58:00
【问题描述】:

我有两个按钮,都启用了自动布局,但在运行时我需要更改它们的 frame 。我改变了但对它们没有影响我通过调用这个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)];

在代码中改变了按钮的框架:

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

请帮我解决这个问题,如何更新约束或如何解决这个问题。提前致谢。

【问题讨论】:

    标签: ios objective-c xcode autolayout nslayoutconstraint


    【解决方案1】:

    在 updateContraints 之前尝试[self.view updateConstraints] 也尝试[self.view layoutIfNeeded]

    编辑:使用常量属性

     @property (nonatomic) NSLayoutConstraint * leftSideButtonContact;
    

    只是

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

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

    【讨论】:

    • 设置框架后什么时候做?
    • 换帧后
    • 如果您使用自动布局,切勿明确更改框架!
    • 对,但是我需要附加leftSideButtonContact 和任何约束吗,因为Xcode 怎么知道leftSideButtonContact 属于哪个按钮?
    • 正打算试试这个。
    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    相关资源
    最近更新 更多