autoLayout 纯代码

SB中拖好空间,让后分别在,Pin,Align,Resolve Auto Layout Issues三个面板中设置好约束就好了。

用存代码的方式给控件添加约束,完成自动布局:

利用NSLayoutConstraint类创建具体的约束对象。apple提供了两种方法

- (void)addConstraint:(NSLayoutConstraint *)constraint;

- (void)addConstraints:(NSArray *)constraints;

在控制器的-viewDidLoad方法里

- (void)viewDidLoad {

    [super viewDidLoad];

    UIView *subView = [UIView allc] initWithFrame:CGRectMake(100,200,100,100)];

    subView.backgroundColor = [UIColor lightGray];

    //设置 autoresizing 无效 不认会把我们的约束无效化

    subView.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:subView];

    //距离父视图左边的距离 约束

    NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelatinEqual toItem:nil attribute:NSLayoutAttributeLeft multiplier:1.0 constant:100];

    //距离父视图顶部的距离 约束

    NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelatinEqual toItem:nil attribute:NSLayoutAttributeTop multiplier:1.0 constant:100];

    //subView 的宽带约束

    NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelatinEqual toItem:nil attribute:NSLayoutAttributeNotAnAtribute multiplier:0.0 constant:100];

    //subView 的高带约束

    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelatinEqual toItem:nil attribute:NSLayoutAttributeNotAnAtribute multiplier:0.0 constant:100];

    

    [self.view addConstraint:leftConstraint];

    [self.view addConstraint:TopConstraint];

    [self.view addConstraint:heightConstraint];

    [self.view addConstraint:widthConstraint];

 

}

 

posted @ 2016-07-06 14:13  wjwdive  阅读(151)  评论(0编辑  收藏  举报