以编程方式更新高度约束
我是新的自动布局。 我从xib文件中完成了我所有的项目,但是现在我遇到了一个问题,我必须以编程方式更新视图的高度。 我已经尝试过,但现在工作。
[[self view] addConstraint:[NSLayoutConstraint constraintWithItem:loginContainer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:loginFrame.size.height]];
在控制台中显示
Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSLayoutConstraint:0x78724530 V:[UIView:0x790cdfb0(170)]>", "<NSLayoutConstraint:0x787da210 V:[UIView:0x790cdfb0(400)]>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x78724530 V:[UIView:0x790cdfb0(170)]> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
您不需要添加新的约束,而需要修改现有约束中的常量。
使用IBOutlet连接到Interface Builder中的约束:
@property (nonatomic, weak) NSLayoutConstraint *heightConstraint;
然后,当您需要以编程方式设置它时,只需在约束上设置常量属性即可:
heightConstraint.constant = 100;
要么
如果无法在Interface Builder中访问该笔尖,请在代码中find该约束:
NSLayoutConstraint *heightConstraint; for (NSLayoutConstraint *constraint in myView.constraints) { if (constraint.firstAttribute == NSLayoutAttributeHeight) { heightConstraint = constraint; break; } } heightConstraint.constant = 100;
而在Swift中:
if let constraint = (myView.constraints.filter{$0.firstAttribute == .width}.first) { constraint.constant = 100.0 }
获取高度约束的参考:在约束中单击+ Ctrl并拖放到您的类文件中:
要更新约束值:
self.heightConstraint.constant = 300; [self.view updateConstraints];
我们来调用你的视图nibView。 所以,你正试图在视图控制器中加载视图,所以首先,在你的视图控制器中,你需要像下面一样加载它:
[[NSBundle mainBundle] loadNibNamed:@"NibView" owner:self options:nil];
然后你需要告诉nibView,你不需要通过这个操作来将自动调整掩码转换成约束
nibView.translatesAutoresizingMaskIntoConstraints = NO;
然后,你可以添加你的约束
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:nibView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:yourValue];
最后只需将其添加到您的视图约束:
[self.view addConstraint:heightConstraint];
你可能也需要添加一个宽度约束。