在使用纯代码添加约束的时候,必须在想要添加的View上调用:[view setTranslatesAutoresizingMaskIntoConstraints:NO]; 否则添加的约束不会起作用。
a. 特别注意 | 的有无
1. 设置view的左右边距和宽度
H:|[aView]|
: aView距离父view的左右边距都是0,宽度可变,即宽度 = 父view的宽度
H:|-20-[aView]-20-|
: aView距离父view的左右边距都是20,宽度可变
H:|-20-[aView(100)]| == H:|-20-[aView(100)] -- 最后一个 | 可以不用写,因为之前的信息已经可以定位view的x值
: aView距离父view的左边距20,宽度100,右边距可变
H:|[aView(100)]-20-| == H:|-0-[aView(100)]-20-|
: 所以右边距的设置不会生效,aView距离父view的左边距0,宽度100,右边距可变
H:[aView(100)]-20-|
: aView距离父view的右边距20,宽度100,左边距可变,左边是没有 | 的
2. 设置view的上下边距和高度
同1,只是H 变成 V
3. 使用constraintWithItem方法来添加高度约束时,toItem要设置为nil。添加到本身还是父view都可以。
NSTextField *textfield = [[NSTextField alloc] init];
textfield.translatesAutoresizingMaskIntoConstraints = NO;
textfield.bordered = YES;
textfield.editable = NO;
textfield.alignment = NSTextAlignmentRight;
textfield.attributedStringValue = [[NSAttributedString alloc] initWithString:@"开启自启动" attributes:nil];
[self addSubview:textfield];
NSDictionary *viewDict = NSDictionaryOfVariableBindings(textfield);
NSArray *cons1 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[textfield]-|" options:0 metrics:nil views:viewDict];
NSArray *cons2 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-30-[textfield]" options:0 metrics:nil views:viewDict];
[self addConstraints:cons1];
[self addConstraints:cons2];