标签:
【上集剧情概要:上集我们主要试着用连式结构写了一个简单地布局的设计的demo,首先通过block方式实现链式调用,然后封装添加布局的约束到block里面,实现了上下左右的简单布局】
好吧,各位观众,接下来抛砖引玉,逐渐去添加一些布局功能的时候到了。。。。。
首先,我们考虑一个问题,因为上集我们主要是默认相对视图为superview,而且都是用默认偏移量constant,并没有倍数关系,那么我们如何加入toItem和multiplier这两个参数呢???
用什么方式展示给用户更为好的呢???
思考中ing..........
好吧,最直接的办法就是添加两个参数,这样就凑齐了。。。。。
ok,我把代码封装了一下,变成下面的样子。。。
#import "UIView+GCFAdditions.h" @implementation UIView (GCFAdditions) - (UIView *(^)(UIView *toItem,float multiplier,NSInteger space))left { return [self addGCFConstraint:NSLayoutAttributeLeft]; } - (UIView *(^)(UIView *toItem,float multiplier,NSInteger space))right { return [self addGCFConstraint:NSLayoutAttributeRight]; } - (UIView *(^)(UIView *toItem,float multiplier,NSInteger space))top { return [self addGCFConstraint:NSLayoutAttributeTop]; } - (UIView *(^)(UIView *toItem,float multiplier,NSInteger space))bottom { return [self addGCFConstraint:NSLayoutAttributeBottom]; } - (UIView *(^)(NSInteger value))width { return ^(NSInteger value) { if (value) { NSLog(@"%ld",(long)value); } else { NSLog(@"%ld",(long)value); } self.translatesAutoresizingMaskIntoConstraints=NO; NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:value]; [self addConstraint:constraint]; return self; }; } - (UIView *(^)(NSInteger value))height { return ^(NSInteger value) { if (value) { NSLog(@"%ld",(long)value); } else { NSLog(@"%ld",(long)value); } self.translatesAutoresizingMaskIntoConstraints=NO; NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:value]; [self addConstraint:constraint]; return self; }; } -(UIView *(^)(UIView *toItem,float multiplier,NSInteger space))addGCFConstraint:(NSLayoutAttribute )att { return ^(UIView *toItem,float multiplier,NSInteger space) { if (space) { NSLog(@"%ld",(long)space); } else { NSLog(@"%ld",(long)space); } self.translatesAutoresizingMaskIntoConstraints=NO; NSLayoutConstraint *constaintTop = [NSLayoutConstraint constraintWithItem:self attribute:att relatedBy:NSLayoutRelationEqual toItem:toItem attribute:att multiplier:1.0 constant:space]; [self.superview addConstraint:constaintTop]; return self; }; } @end
添加了width和height两个属性
在调用里面使用变成:
self.view1.left(self.view,1,50) .right(self.view,1,-50) .top(self.view,1,100) .height(130); self.view2.left(self.view,1,50) .right(self.view,1,-50) .top(self.view1,1,100) .height(130); self.view3.left(self.view,1,50) .right(self.view,1,-50) .top(self.view2,1,100) .height(130);
到这里我们完成了对原生的NSLayoutConstraint的封装
标签:
原文地址:http://www.cnblogs.com/guchengfengyun/p/5853222.html