更多技术性文章请关注 合伙呀

 

自动布局:通过创建约束条件来完成在系统内定制用户界面位置和大小的方法
 UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"我是按钮" forState:UIControlStateNormal];
    button.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:button];
    //当视图需要使用约束条件自动布局功能时,需要关闭视图的自动改变大小功能
    [button setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    //创建横向约束条件
    NSArray *contraintsH=[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[button]-20-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button)];
    //创建竖向约束条件
    NSArray *contraintsV=[NSLayoutConstraint constraintsWithVisualFormat:@"V:[button(30)]-20-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button)];
    //将约束条件添加到根视图上
    [self.view addConstraints:contraintsH];
    [self.view addConstraints:contraintsV];
    
    UIView *view=[[UIView alloc]init];
    view.backgroundColor=[UIColor redColor];
    [self.view addSubview:view];
    
    [view setTranslatesAutoresizingMaskIntoConstraints:NO];
    view.center=self.view.center;
    NSArray *ViewcontraintsH=[NSLayoutConstraint constraintsWithVisualFormat:@"H:[view(100)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view,button)];
    NSArray *viewContraintsV=[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view(200)]-30-[button]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view,button)];
    [self.view addConstraints:ViewcontraintsH];
    [self.view addConstraints:viewContraintsV];