[英]Enable AutoLayout in a UIView when adding constraints programmatically
I have a UIView. 我有一个UIView。 It is nothing fancy.
这没什么特别的。 The code is below.
代码如下。 The problem is that when I run the app, updateConstraints is never called, so the constraints don't do anything.
问题是,当我运行应用程序时,从不调用updateConstraints,因此约束不会执行任何操作。
I am used to doing everything by computing the coordinates manually. 我习惯通过手动计算坐标来做所有事情。 The containing view does exactly that.
包含视图就是这样做的。 So I may be missing some piece I need to turn the constraints on.
所以我可能会错过一些我需要转动限制的部分。 What could it be?
会是什么呢?
@implementation Subview
-(void) createFooButton {
UIButton* foo = [[UIButton alloc]init];
self.fooButton = foo;
[foo setTitle:@"foo" forState:UIControlStateNormal];
[foo sizeToFit];
[self addSubview:foo];
UIColor* green = [UIColor greenColor];
foo.translatesAutoresizingMaskIntoConstraints = NO;
[foo setBackgroundColor:green];
}
-(void) createBarButton {
UIButton* bar = [[UIButton alloc]init];
[bar sizeToFit];
self.barButton = bar;
[bar setTitle:@"bar" forState:UIControlStateNormal];
bar.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:bar];
UIColor* red = [UIColor redColor];
[bar setBackgroundColor:red];
}
-(void) addLayoutConstraints {
UIButton* foo = self.fooButton;
UIButton* bar = self.barButton;
NSLayoutConstraint* constraint = [NSLayoutConstraint constraintWithItem:foo attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:100];
NSLayoutConstraint* constraint2 = [NSLayoutConstraint constraintWithItem:bar attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:foo attribute:NSLayoutAttributeBottom multiplier:1 constant:20];
NSArray* array = @[constraint, constraint2];
[self addConstraints: array];
}
-(void) updateConstraints {
[self addLayoutConstraints];
[super updateConstraints];
}
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
self.backgroundColor = [UIColor cyanColor];
[self createFooButton];
[self createBarButton];
self.autoresizesSubviews = false;
self.translatesAutoresizingMaskIntoConstraints = NO;
}
return self;
}
@end
You can force the system to use auto layout by adding this to SubView
: 您可以通过将其添加到
SubView
来强制系统使用自动布局:
+ (BOOL)requiresConstraintBasedLayout {
return YES;
}
Notice that this is a class method, not an instance method. 请注意,这是一个类方法,而不是实例方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.