我们来做一个把button放在父控件中间的例子
<书上源码>
- (void)viewDidLoad{
[super viewDidLoad];
/* 1) Create our button */
self.button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.button.translatesAutoresizingMaskIntoConstraints = NO;
[self.button setTitle:@"Button" forState:UIControlStateNormal];
[self.view addSubview:self.button];
UIView *superview = self.button.superview;
/* 2) Create the constraint to put the button horizontally in the center */
NSLayoutConstraint *centerXConstraint =
[NSLayoutConstraint constraintWithItem:self.button
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.0f];
/* 3) Create the constraint to put the button vertically in the center */
NSLayoutConstraint *centerYConstraint =
[NSLayoutConstraint constraintWithItem:self.button
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeCenterY
multiplier:1.0f
constant:0.0f];
/* Add the constraints to the superview of the button */
[superview addConstraints:@[centerXConstraint, centerYConstraint]];
}
采用这种方式来对齐button中,不管是旋转设备,或是在不同设备上phone 或 pad上,都能让button置于屏幕中间。采用这种方式我们甚至不需要设置button的frame,也不需要监听旋转事件来调整布局。不过话又说回来了,如果我们想设置button的frame,我们就不得不对每一种设备的每一个方向设置frame。
在我的例子中,对上例的button设置frame,则设置的frame没有效果,需要把这一句self.button.translatesAutoresizingMaskIntoConstraints = NO;注释掉才有效果。不过这一句注释掉的话contraint就没效果了。菜鸟还是不懂