http://blog.csdn.net/zfpp25_/article/details/8861221
http://blog.csdn.net/zfpp25_/article/details/8861855
http://blog.csdn.net/zfpp25_/article/details/8861958
http://blog.csdn.net/zfpp25_/article/details/8862040
http://blog.csdn.net/zfpp25_/article/details/8862157
继IOS6之AutoLayout(一)简单讲解了的”上沿“、”下沿“、”左沿“、”右沿“相对布局方法之后,本篇讲解相对布局中的居中。
直接看实现代码:
UIButton *secondButton = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
[secondButtonsetTitle:@"Second"forState:UIControlStateNormal];
[secondButton sizeToFit];
secondButton.translatesAutoresizingMaskIntoConstraints =NO;
[self.viewaddSubview:secondButton];
NSLayoutConstraint *constraint;
//secondButton的中心点的X坐标与self.view的中心点X坐标距离为零,也就是中心点X坐标重合
constraint = [NSLayoutConstraint
constraintWithItem:secondButton
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.0f];
[self.view addConstraint:constraint];
//secondButton的中心点的X坐标与self.view的中心点Y坐标距离为零,也就是中心点Y坐标重合
constraint = [NSLayoutConstraint
constraintWithItem:secondButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.0f
constant:0.0f];
// 指定按钮的宽度为200.0f
constraint = [NSLayoutConstraint
constraintWithItem:secondButton
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem: nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:200.0f];
[self.view addConstraint:constraint];
// 指定按钮的高度为60.0f
constraint = [NSLayoutConstraint
constraintWithItem:secondButton
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem: nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:60.0f];
[self.view addConstraint:constraint];
以上代码中,指定按钮中心点的相对左边容易理解,但指定宽度和高度的时候,NSLayoutAttributeNotAnAttribute如何理解 ?
下面是官网的解释:
Constraints are of the form "view1.attr1 <relation> view2.attr2 * multiplier + constant". If the constraint you wish to express does not have a second view and attribute, use nil and NSLayoutAttributeNotAnAttribute
.
其实也不难理解了。如果有不理解内容可参考IOS6之AutoLayout(一)
转载请保留,原文链接:http://blog.csdn.net/lizhongfu2013/article/details/8861855
若发现有不合适或错误之处,还请批评指正,不胜感激。