更加快速地设置Frame

由于现在手头上的项目是基于frame开发的,没有xib或者storyboard,没有使用自动布局,所以排布界面时总是显得很繁琐。

令人蛋疼的frame布局

老代码对界面的坐标尺寸设置都是通过下面的方式:

...
UIView * mainView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height, self.width, MAIN_HEIGHT)];
[mainView setBackgroundColor:[UIColor whiteColor]];
[self addSubview:mainView];
self.mainView = mainView;

UIView * opertionMenu = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 45)];
[opertionMenu setBackgroundColor:[UIColor whiteColor]];
[mainView addSubview:opertionMenu];

UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 44, self.width, 1)];
[line setBackgroundColor:[UIColor colorWithHex:0xe9e9e9]];
[opertionMenu addSubview:line];
...

这些坐标设置工作都是在初始化,也就是init系列方法中完成的。这样做的弊端很明显,复用性很差,如果还是按照这种方式的话,每扩展一种界面类型,就要新增一个init方法。久而久之,冗余代码会越来越多,新增特性想重用这块控件的话,需要做比较多的无用功。

由于上面代码很多针对坐标尺寸的设置都是在init系列方法中完成的,所以很少有单独修改frame中的某个成员的操作,不过旧代码还是提供了快速设置某个成员的方法:

@interface UIView (Size)
...
- (CGFloat)width;
- (CGFloat)height;
- (CGFloat)minX;
- (CGFloat)midX;
- (CGFloat)maxX;
- (CGFloat)minY;
- (CGFloat)midY;
- (CGFloat)maxY;
...
@end

很明显地看出,这种分类命名是有问题的(这也是直接导致我后续没有引入masonry的诱因之一,旧代码中过多的使用了以上分类,和简易的masonry用法即没有mas前缀的方法产生的冲突过多)。

于是我新增了一些快速设置的坐标的分类方法:

@interface UIView (Size)
...
@property (assign, nonatomic) CGFloat bq_y;
@property (assign, nonatomic) CGFloat bq_x;
@property (assign, nonatomic) CGFloat bq_width;
@property (assign, nonatomic) CGFloat bq_height;
@property (assign, nonatomic) CGFloat bq_centerX;
@property (assign, nonatomic) CGFloat bq_centerY;
@property (assign, nonatomic) CGPoint bq_origin;
@property (assign, nonatomic) CGSize bq_size;
@property (assign, nonatomic) CGFloat bq_maxX;
@property (assign, nonatomic) CGFloat bq_maxY;
@property (assign, nonatomic, readonly) CGPoint bq_subCenter;
@property (assign, nonatomic, readonly) CGFloat bq_subCenterX;
@property (assign, nonatomic, readonly) CGFloat bq_subCenterY;
- (instancetype)bq_sizeToFit;
...
@end

于是代码中就多了另外一种设置frame的书写格式:

- (void)adjustSubviewFrame {
    ...
    if (!_timeLabel.hidden) {
        [_timeLabel sizeToFit];
        CGFloat timeLabelLRMargin = 5;
        CGFloat timeLabelTopMaigin = BQMessageCommonMargin;
        _timeLabel.bq_size = CGSizeMake(_timeLabel.bq_width + 2 * timeLabelLRMargin, BQMessageTimeHeight);
        _timeLabel.center = CGPointMake(self.contentView.bq_centerX, timeLabelTopMaigin + _timeLabel.bq_height * 0.5);
    } else {
        _timeLabel.frame = CGRectZero;
    }
    CGFloat headImageEdgeMargin = BQMessageCommonMargin;
    CGFloat headImageViewX = _isSelf ? self.contentView.bq_width - _headIconImageView.bq_width - headImageEdgeMargin : headImageEdgeMargin;
    CGFloat headImageViewY = CGRectGetMaxY(_timeLabel.frame) + headImageEdgeMargin;
    _headIconImageView.bq_origin = CGPointMake(headImageViewX, headImageViewY);
    if (!_identityButton.hidden) {
        CGFloat identifyButtonTopMargin = BQMessageHeaderBottomMargin;
        CGFloat identifyButtonY = CGRectGetMaxY(_headIconImageView.frame) + identifyButtonTopMargin;
        _identityButton.bq_y = identifyButtonY;
        _identityButton.bq_centerX = _headIconImageView.bq_centerX;
    }
    CGFloat nameLabelToHeadImageTopMargin = 0;
    if (!_nameLabel.hidden) {
        [_nameLabel sizeToFit];
        CGFloat nameLabelX = CGRectGetMaxX(_headIconImageView.frame) + headImageEdgeMargin;
        CGFloat nameLabelY = _headIconImageView.bq_y + nameLabelToHeadImageTopMargin;
        _nameLabel.bq_origin = CGPointMake(nameLabelX, nameLabelY);
    }
    ...
}

把设置可变坐标的代码独立出来放进一个方法中增强的控件的复用性,但是也无形中增加了布局代码代码量,而且估计第二个人来看这个计算过程也会很头大。

能不能采用链式的方式简化对界面进行frame布局的代码?于是我借鉴了masonry的实现方式,弄了一套快速设置frame的代码。最终使用的效果:

UIView *v1 = [UIView new];
v1.tpc_quickAttribute
.referToView(self.view)
.addToView(self.view)
.alignOrigin(CGPointMake(10, 20))
.alignSize(CGSizeMake(-200, -400))
.backgroundColor([UIColor redColor]);

UIView *v2 = [UIView new];
v2.tpc_quickAttribute
.referToView(v1)
.addToView(v1)
.size(CGSizeMake(20, 20))
.alignCenter(pzero)
.backgroundColor([UIColor orangeColor]);

UIView *v3 = [UIView new];
v3.tpc_quickAttribute
.addToView(self.view)
.referToView(v1)
.alignSize(CGSizeMake(20, 20))
.referToView(self.view)
.alignRightToRight(20)
.alignBottomToBottom(20)
.backgroundColor([[UIColor grayColor] colorWithAlphaComponent:0.4]);

顿时感觉整个世界又变清新了。。。

实现的思路

首先,给UIView绑定一个布局实例:

<UIView+TPCQuickAttribute.m>

- (TPCQuickAttribute *)tpc_quickAttribute {
    TPCQuickAttribute *quickAttribute = objc_getAssociatedObject(self, _cmd);
    if (!quickAttribute) {
        quickAttribute = [[TPCQuickAttribute alloc] initWithView:self];
        objc_setAssociatedObject(self, _cmd, quickAttribute, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return quickAttribute;
}

这个TPCQuickAttribute就是进行快速设置frame的关键:

<TPCQuickAttribute.h>

#if TPC_OPEN_LOG == 1
#ifdef DEBUG
#define TPCLayoutLog(s, ... ) NSLog( @"<%s:(%d)> %@", __FUNCTION__, __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] ) 
#else
#define TPCLayoutLog(s, ... )
#endif
#else
#define TPCLayoutLog(s, ... )
#endif
@interface TPCQuickAttribute : NSObject <TPCQuickProtcol>
- (instancetype)initWithView:(UIView *)view;
@property (weak, nonatomic, readonly) UIView *view;
@property (weak, nonatomic) UIView *referView;
@property (assign, nonatomic, readonly) BOOL referViewIsSuperview;

- (TPCQuickAttribute *(^)(UIView * view))referToView;
- (TPCQuickAttribute *(^)(UIView *))addToView;
- (void)end;
@end

这个类包含了要进行布局的view对象,还有进行参考的referView。

一旦设置好了这两者,就可以进行下一步操作了:

<TPCQuickAttribute+Frame.m>
...
- (TPCQuickAttribute *(^)(CGFloat))alignLeftToLeft {
    return ^TPCQuickAttribute *(CGFloat offset) {
        return self.x(self.referViewX + offset);
    };
}

- (TPCQuickAttribute *(^)(CGFloat))alignLeftToRight {
    return ^TPCQuickAttribute *(CGFloat offset) {
        return self.alignLeftToLeft(self.referView.frame.size.width + offset);
    };
}
...

上面代码参考referView,对view的x坐标进行设置。对于这种链式的实现原理,就是利用了返回的block是一个无名函数,可以通过( )执行,这样对上面的方法进行调用,产生以下效果:

xxx.alignLeftToLeft(0)

了解了block的使用方式就没什么复杂的了。

既然可以快速设置frame,那么常用属性呢?再增加一个分类:

<TPCQuickAttribute+Appearance.m>
...
- (TPCQuickAttribute *(^)(UIColor *))backgroundColor {
    return ^TPCQuickAttribute *(UIColor *backgroundColor) {
        self.view.backgroundColor = backgroundColor;
        return self;
    };
}

- (TPCQuickAttribute *(^)(UIViewContentMode))contentMode {
    return ^TPCQuickAttribute *(UIViewContentMode contentMode) {
        self.view.contentMode = contentMode;
        return self;
    };
}

...

同理,综合上面的代码,就可以链式地写出设置frame的代码了。

小结

当然,现在有了自动布局,一般界面已经不需要使用frame进行布局了,代码的自动布局可以使用masonry,我私下也喜欢用storyboard+xib的方式写一些小demo。

所以以上代码纯属玩票==。

代码链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容