ios中vfl怎样添加约束等级

ios中vfl怎样添加约束等级,第1张

第一种:

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

第二种:

+ (NSArray *)constraintsWithVisualFormat:(NSString *)format options:(NSLayoutFormatOptions)opts metrics:(NSDictionary *)metrics views:(NSDictionary *)views

第一种方法返回的是一个约束对象,也就是一条约束。看参数也比较好理解,就是在view1与view2之间设定一条约束,但往往一个控件需要好几条约束来约束,加上如此长的方法,所以导致一个控件就需要大量的代码来实现约束。

第二种方法返回的是array,包含的是一组约束,所以一般一个控件,调用两次第二种方法就能实现约束。所以这种方法更加的简洁,但是这种方法用到的是一种描述性语言,有点不好理解

假设你有这么一个 view

UIView *view = [[UIView alloc] init]

view.backgroundColor = [UIColor redColor]

view.translatesAutoresizingMaskIntoConstraints = NO

[self.view addSubview:view]

如果你不考虑 Storyboard 的话,这东西如果你用原生 NSLayoutConstraint,要写这么一堆玩意儿(知乎的代码格式化真恶心):

// NSLayoutConstraint

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:view

attribute:NSLayoutAttributeWidth

relatedBy:NSLayoutRelationEqual

toItem:self.view

attribute:NSLayoutAttributeWidth

multiplier:1

constant:0]]

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:view

attribute:NSLayoutAttributeHeight

relatedBy:NSLayoutRelationEqual

toItem:nil

attribute:NSLayoutAttributeHeight

multiplier:0

constant:40]]

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:view

attribute:NSLayoutAttributeBottom

relatedBy:NSLayoutRelationEqual

toItem:self.view

attribute:NSLayoutAttributeBottom

multiplier:1

constant:0]]

如果是 VFL,可以简化成这样:

// VFL

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|"

options:0

metrics:nil

views:NSDictionaryOfVariableBindings(view)]]

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view(==40)]|"

options:0

metrics:nil

views:NSDictionaryOfVariableBindings(view)]]

但是如果是 Masonry!

// Masonry

[view mas_makeConstraints:^(MASConstraintMaker *make) {

make.left.right.bottom.equalTo(self.view)

make.height.equalTo(40)

}]

Bazinga! 所以在你弄懂 Auto Layout 之后,我觉得还是用 Masonry 吧..

用第一个ViewController的uiview添加另外一个viewController的view例如[self.view addSubView viewController.view]


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11613904.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存