以编码的方式实现Auto Layout自动布局(二)

在上一篇文章iOS学习笔记02——以编码的方式实现Auto Layout自动布局(一)中我们简单的介绍了使用Visual Format Language创建布局约束来实现自动布局,这种方法创建的布局约束能够满足大部分的布局的需求。但是想要实现类似于这样的约束:button.width = 2 * button.height就不能满足要求了,这一篇我们我们简单介绍一下如何创建这样的布局约束。

Apple就是非常贴心,它为我们提供了另外一个方法创建类似于view1.attr1 = view2.attr2 * multiplier + constant这样的约束,方法如下:

  1. +(id)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;  

下面我们用这种方法创建一个布局约束,实现一个按钮button的布局,button距离父视图的左侧60点,距离顶部30点,其中宽度W = 2 * H + 10。效果图如下


不多说,上代码

  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     // Do any additional setup after loading the view.  
  5.     self.edgesForExtendedLayout = UIRectEdgeNone;  
  6.       
  7.     UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];  
  8.     button.layer.borderColor = [UIColor blackColor].CGColor;  
  9.     button.layer.borderWidth = 2.0;  
  10.     [button setTitle:@"W=2*H" forState:UIControlStateNormal];  
  11.     [self.view addSubview:button];  
  12.       
  13.     [button setTranslatesAutoresizingMaskIntoConstraints:NO];  
  14.       
  15.     NSMutableArray * tempConstraints = [NSMutableArray array];  
  16.       
  17.     [tempConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-60-[button]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button)]];  
  18.     [tempConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-30-[button(==30)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button)]];  
  19.       
  20.     [self.view addConstraints:tempConstraints];  
  21.       
  22.     [self.view addConstraint:[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:button attribute:NSLayoutAttributeHeight multiplier:2.0 constant:10.0]];  
  23. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值