本文主要是介绍NSLayoutConstraint,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
NSLayoutConstraint
使用下面代码测试自动布局使用程序写
增加测试UIButton代码:
UIButton* onHelpView = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
[onHelpView setTitle:@"mgen" forState:UIControlStateNormal];
onHelpView.backgroundColor = [UIColorgreenColor];
[self.view addSubview:onHelpView];
//禁止自动转换AutoresizingMask
onHelpView.translatesAutoresizingMaskIntoConstraints =NO;
[self.view addSubview:onHelpView];
使用NSLayoutConstraint
NSMutableArray *array = [NSMutableArrayarrayWithArray: [NSLayoutConstraintconstraintsWithVisualFormat:@"|[onHelpView]|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(onHelpView)]];
[array addObjectsFromArray:[NSLayoutConstraintconstraintsWithVisualFormat:@"V:|[onHelpView]|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(onHelpView)]];
[self.view addConstraints:array];
另一种写法
[self.viewaddConstraint:[NSLayoutConstraint
constraintWithItem:onHelpView
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1
constant:0]];
[self.viewaddConstraint:[NSLayoutConstraint
constraintWithItem:onHelpView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1
constant:0]];
[self.viewaddConstraint:[NSLayoutConstraint
constraintWithItem:onHelpView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:1
constant:0]];
//定义高度是父View的三分之一
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:onHelpView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:1
constant:0]];
两种效果相同。
再加上KVO测试代码
[onHelpView addObserver:self forKeyPath:@"bounds" options:NSKeyValueObservingOptionNew |NSKeyValueObservingOptionInitial context:nil];
//KVO回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (object == onHelpView && [keyPath isEqualToString:@"bounds"])
{[onHelpView setTitle:NSStringFromCGSize(onHelpView.bounds.size) forState:UIControlStateNormal];
}
转载传送门:http://blog.csdn.net/djl4104804/article/details/20768901
这篇关于NSLayoutConstraint的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!