反复写相同的属性让我感到疲倦,所以我写了一个小类别来帮助我。
以下三行代码
[someView addConstraint:[NSLayoutConstraint wes_constraintWithItem:anotherView
attribute:NSLayoutAttributeWidth
toItem:someView]];
等同于
[someView addConstraint:[NSLayoutConstraint constraintWithItem:anotherView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:someView
attribute:NSLayoutAttributeWidth
multiplier:1.0f
constant:0.0f]];
您可以看到,有很多重复的值。谢谢了。
您甚至可以这样做
[someView addConstraints:[NSLayoutConstraint wes_constraintWithItem:anotherView
size:CGSizeMake(100, 50)]];
这相当于
[someView addConstraint:[NSLayoutConstraint constraintWithItem:anotherView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:100.0f]];
[someView addConstraint:[NSLayoutConstraint constraintWithItem:anotherView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:50.0f]];
挺不错的,对吧?
如您所见,我只去掉了常用且常留空的一些属性和属性。
嗯,这里列出所有可用的助手
/// Returns an array of constraints to set up a view's size
+ (NSArray *)wes_constraintWithItem:(id)view1 size:(CGSize)size;
/// Returns a constraint with two views that will use have the same relation with that specific attribute
+ (instancetype)wes_constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 toItem:(id)view2;
/// Returns a constraint with two views that will use have the same relation with that specific attribute, however you can now set the constant
+ (instancetype)wes_constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 toItem:(id)view2 constant:(CGFloat)c;
/// Returns a constraint with two views that will use the equal relation, however, you're free to set two different attributes and a constant
+ (instancetype)wes_constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 constant:(CGFloat)c;
您可以在twitter上找到我,@wesslansimon。