AutoLayout初战----Masonry与FDTemplateLayoutCell实践
学iOS也有几个月了。一直都是纯代码开发,菜鸟入门,到今天还处在Frame时代。刚好近期项目在提审。有点时间能够学学传说中的AutoLayout。事实上。就是android的相对布局(RelativeLayout),没了解之前一直认为非常神奇,今天学习了一下,才发现AutoLayout也不是那么神奇不可触碰.
在frame时代,一切数据在我们手中都是一个个坐标,我们所要做的,就是用数据反推控件的大小,然后显示出来。只是,自从i6出了之后,屏幕的宽度也不再是固定的了。AutoLayout是大势所趋。
在AutoLayout时代,我们不须要用数据去反推控件大小。而是我们给控件加入约束,告诉控件。你该在大概哪个地方,比方,距离SuperVIew的左边20个点,距离SuperView的上边10个点,接触过android开发的人应该会对这个概念比較熟悉。然后系统帮我们自己主动计算出frame。
近期也研究过用Storyboard为控件加约束。相对于纯代码来说简单非常多,只是,还是怕多人开发出现故障,还是用了纯代码来实现了。
如题。这次我是使用了Masonry来完毕AutoLayout,这里有一篇关于Masonry的介绍Masonry介绍与使用实践:高速上手Autolayout,这个开源项目已经帮我们将iOS比較复杂的AutoLayout封装起来,使用起来也比較方便。
FDTemplateLayoutCell能够帮助我们计算cell的高度而且缓存起来,使用也是很方便。关于FDTemplateLayoutCell的介绍能够看这篇文章:优化UITableViewCell高度计算的那些事。
本篇文章所用demo所用到的数据和图片来自于FDTemplateLayoutCell的demo,本demo也是參考FDTemplateLayoutCell demo的Storyboard布局,自己用纯代码加上了约束。
ViewController.m
//
// ViewController.m
// 结合Masonry和FDTemplateLayoutCell,自己第一个autolayout小demo,数据来自FDTemplateLayoutCell的demo,整个demo是參考FDTemplateLayoutCell demo的Storyboard布局自己用Masonry加入约束
//
// Created by crw on 15/8/13.
// Copyright (c) 2015年 crw. All rights reserved.
// 原文出处https://github.com/forkingdog/UITableView-FDTemplateLayoutCell #import "ViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "FDFeedEntity.h"
#import "AutoTableViewCell.h" @interface ViewController ()<UITableViewDataSource,UITableViewDelegate>{
UITableView *mTableView;
}
@property (nonatomic, strong) NSMutableArray *feedEntitySections;
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
mTableView = [[UITableView alloc] initWithFrame:self.view.frame];
[self.view addSubview:mTableView]; mTableView.dataSource = self;
mTableView.delegate = self;
[mTableView registerClass:[AutoTableViewCell class] forCellReuseIdentifier:@"AutoTableViewCell"]; mTableView.estimatedRowHeight = 200;//预算行高
mTableView.fd_debugLogEnabled = YES;//开启log打印高度
[self buildTestDataThen:^{
[mTableView reloadData];
}];
} - (void)buildTestDataThen:(void (^)(void))then{
// Simulate an async request
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Data from `data.json`
NSString *dataFilePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:dataFilePath];
NSDictionary *rootDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *feedDicts = rootDict[@"feed"]; // Convert to `FDFeedEntity`
NSMutableArray *entities = @[].mutableCopy;
[feedDicts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[entities addObject:[[FDFeedEntity alloc] initWithDictionary:obj]];
}];
self.feedEntitySections = entities; // Callback
dispatch_async(dispatch_get_main_queue(), ^{
!then ? : then();
});
});
} -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
AutoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AutoTableViewCell" forIndexPath:indexPath];
[self configureCell:cell atIndexPath:indexPath];
return cell;
} - (void)configureCell:(AutoTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath{
cell.fd_enforceFrameLayout = NO; // Enable to use "-sizeThatFits:"
if (indexPath.row % 2 == 0) {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
} else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
cell.entity = self.feedEntitySections[indexPath.row];
} -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//高度计算而且缓存
return [tableView fd_heightForCellWithIdentifier:@"AutoTableViewCell" cacheByIndexPath:indexPath configuration:^(AutoTableViewCell *cell) {
[self configureCell:cell atIndexPath:indexPath];
}];
} -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.feedEntitySections.count;
} -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
FDFeedEntity *obj = self.feedEntitySections[indexPath.row];
obj.title = @"OH。NO,TITLE CLICK";
obj.content = @"Let our rock! 。。";
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end
mTableView.estimatedRowHeight = 200;//预算行高
依据FDTemplateLayoutCell,启动估算行高能够加速高度的计算,下面是原文:
About estimatedRowHeight
estimatedRowHeight helps to delay all cells' height calculation from load time to scroll time.
Feel free to set it or not when you're using FDTemplateLayoutCell.If you use "cacheByIndexPath" API,
setting this estimatedRowHeight property is a better practice for imporve load time, and it DOES NO LONGER
affect scroll performance because of "precache".
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//高度计算而且缓存
return [tableView fd_heightForCellWithIdentifier:@"AutoTableViewCell" cacheByIndexPath:indexPath configuration:^(AutoTableViewCell *cell) {
[self configureCell:cell atIndexPath:indexPath];
}];
}
FDTemplateLayoutCell提供的计算cell高的代码。轻松解决行高计算。而且缓存起来.
接下来。重头戏都在我们的AutoTableViewCell.m
//
// AutoTableViewCell.m
// TableViewAuto
//
// Created by crw on 15/8/13.
// Copyright (c) 2015年 crw. All rights reserved.
// #import "AutoTableViewCell.h"
#import "Masonry.h"
#define margin 10
#define WS(weakSelf) __weak __typeof(&*self)weakSelf = self;
@interface AutoTableViewCell(){
MASConstraint *constraint_content;/**<内容上边距为5的约束,没内容时将边距设置为0 */
MASConstraint *constraint_mainImageView;
MASConstraint *constraint_userNameLabel;
}
@end @implementation AutoTableViewCell - (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
self.contentView.bounds = [UIScreen mainScreen].bounds;
} - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
[self setAutoLayout];
}
return self;
} - (void)addView:(UIView *)view{
[self.contentView addSubview:view];
} - (void)setAutoLayout{
WS(ws);
_titleLabel = [[UILabel alloc] init];
_titleLabel.numberOfLines = 0;
//_titleLabel.backgroundColor = [UIColor redColor];
[self addView:_titleLabel]; _contentLabel = [[UILabel alloc] init];
_contentLabel.numberOfLines = 0;
_contentLabel.font = [UIFont systemFontOfSize:14];
_contentLabel.textColor = [UIColor grayColor];
//_contentLabel.backgroundColor = [UIColor purpleColor];
[self addView:_contentLabel]; _mainImageView = [[UIImageView alloc] init];
_mainImageView.contentMode = UIViewContentModeScaleAspectFill;
_mainImageView.clipsToBounds = YES;
//_mainImageView.backgroundColor = [UIColor orangeColor];
[self addView:_mainImageView]; _userNameLabel = [[UILabel alloc] init];
//_userNameLabel.backgroundColor = [UIColor greenColor];
_userNameLabel.textColor = [UIColor orangeColor];
_userNameLabel.font = [UIFont systemFontOfSize:12];
[self addView:_userNameLabel]; _timeLabel = [[UILabel alloc] init];
_timeLabel.textColor = [UIColor blueColor];
_timeLabel.font = [UIFont systemFontOfSize:12];
//_timeLabel.backgroundColor = [UIColor blueColor];
[self addView:_timeLabel]; [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.equalTo(ws.contentView).offset(margin);
make.trailing.equalTo(ws.contentView.mas_trailing).offset(-margin);
make.top.equalTo(ws.contentView).offset(margin);
}]; [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.equalTo(_titleLabel.mas_left);
make.right.equalTo(ws.contentView.mas_right).offset(-margin);
//下面设置距离title的边距,设置两条优先度不同的约束,内容为空时将优先度高的约束禁用
make.top.equalTo(_titleLabel.mas_bottom).priorityLow();//优先度低,会被优先度高覆盖
constraint_content = make.top.equalTo(_titleLabel.mas_bottom).offset(5).priorityHigh();
}]; [_mainImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(_titleLabel.mas_left);
make.height.greaterThanOrEqualTo(@0);
make.right.lessThanOrEqualTo(ws.contentView.mas_right).offset(-margin);
make.top.equalTo(_contentLabel.mas_bottom).priorityLow();
constraint_mainImageView = make.top.equalTo(_contentLabel.mas_bottom).offset(5).priorityHigh();
}]; [_userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(_titleLabel.mas_left);
make.top.equalTo(_mainImageView.mas_bottom).priorityLow();
constraint_userNameLabel = make.top.equalTo(_mainImageView.mas_bottom).offset(5).priorityHigh();
}]; [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(ws.contentView.mas_right).offset(-margin);
make.top.equalTo(_userNameLabel.mas_top);
make.bottom.equalTo(self.contentView.mas_bottom).offset(-margin);
}];
} - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated]; // Configure the view for the selected state
} - (void)setEntity:(FDFeedEntity *)entity
{
_entity = entity; self.titleLabel.text = entity.title;
self.contentLabel.text = entity.content;
self.mainImageView.image = entity.imageName.length > 0 ? [UIImage imageNamed:entity.imageName] : nil;
self.userNameLabel.text = entity.username;
self.timeLabel.text = entity.time; self.contentLabel.text.length == 0 ?[constraint_content deactivate]:[constraint_content activate];
self.mainImageView.image == nil?[constraint_mainImageView deactivate]:[constraint_mainImageView activate];
self.userNameLabel.text.length== 0 ? [constraint_userNameLabel deactivate]:[constraint_userNameLabel activate];
} #if 0 // If you are not using auto layout, override this method
- (CGSize)sizeThatFits:(CGSize)size
{
CGFloat totalHeight = 0;
totalHeight += [self.titleLabel sizeThatFits:size].height;
totalHeight += [self.contentLabel sizeThatFits:size].height;
totalHeight += [self.mainImageView sizeThatFits:size].height;
totalHeight += [self.userNameLabel sizeThatFits:size].height;
totalHeight += 40; // margins
return CGSizeMake(size.width, totalHeight);
} #endif @end
在setAutoLayout里面。是我们AutoLayout的主要代码,加须要的view加到contentView。用Masonry给每一个view加入了约束。代码和原生的相比,比較好理解。
- (CGSize)sizeThatFits:(CGSize)size
FDTemplateLayoutCell支持两种模式的算高。AutoLayout和Frame.下面是官方原文:
Frame layout mode
FDTemplateLayoutCell offers 2 modes for asking cell's height.
- Auto layout mode using "-systemLayoutSizeFittingSize:"
- Frame layout mode using "-sizeThatFits:"
Generally, no need to care about modes, it will automatically choose a proper mode by whether you have set auto layout constrants on cell's content view. If you want to enforce frame layout mode, enable this property in your cell's configuration
block:
cell.fd_enforceFrameLayout = YES;
And if you're using frame layout mode, you must override -sizeThatFits: in your customized cell and return content
view's height (separator excluded)
- (CGSize)sizeThatFits:(CGSize)size
{
return CGSizeMake(size.width, A+B+C+D+E+....);
}
FDTemplateLayoutCell有两种计算高度的模式
1.一种是AutoLayout使用的-systemLayoutSizeFittingSize:
2.还有一种是Frame使用的-sizeThatFits:
能够通过fd_enforceFrameLayout = YES 开启Frame模式,注意。开启Frame模式须要重写- (CGSize)sizeThatFits,例如以下:
- (CGSize)sizeThatFits:(CGSize)size
{
return CGSizeMake(size.width, A+B+C+D+E+....);
}
AutoLayout初战----Masonry与FDTemplateLayoutCell实践的更多相关文章
- AutoLayout框架Masonry使用心得
AutoLayout框架Masonry使用心得 字数1769 阅读1481 评论1 喜欢17 我们组分享会上分享了页面布局的一些写法,中途提到了AutoLayout,会后我决定将很久前挖的一个坑给填起 ...
- iOS开发通过代码方式使用AutoLayout (NSLayoutConstraint + Masonry)
iOS开发通过代码方式使用AutoLayout (NSLayoutConstraint + Masonry) 随着iPhone6/6+设备的上市,如何让手头上的APP适配多种机型多种屏幕尺寸变得尤为迫 ...
- iOS AutoLayout自动布局&Masonry介绍与使用实践
Masonry介绍与使用实践:快速上手Autolayout http://www.cnblogs.com/xiaofeixiang/p/5127825.html http://www.cocoachi ...
- Masonry和FDTemplateLayoutCell 结合使用示例Demo
我们知道,界面布局可以用Storyboard或Xib结合Autolayout实现,如果用纯代码布局,比较热门的有Masonry.SDAutoLayout,下面的简单demo,采用纯代码布局,实现不定高 ...
- 【转】有趣的Autolayout示例-Masonry实现
原文网址:http://tutuge.me/2015/05/23/autolayout-example-with-masonry/ 好久没有写Blog了,这段时间有点忙啊=.=本文举了3个比较有“特点 ...
- 代码方式使用AutoLayout (NSLayoutConstraint + Masonry)
随着iPhone6/6+设备的上市,如何让手头上的APP适配多种机型多种屏幕尺寸变得尤为迫切和必要.(包括:iPhone4/4s,iPhone5/5s,iPhone6/6s,iPhone 6p/6ps ...
- iOS — Autolayout之Masonry解读
前言 1 MagicNumber -> autoresizingMask -> autolayout 以上是纯手写代码所经历的关于页面布局的三个时期 在iphone1-iphone3gs时 ...
- IOS开发通过代码方式使用AutoLayout (NSLayoutConstraint + Masonry) 转载
http://blog.csdn.net/he_jiabin/article/details/48677911 随着iPhone6/6+设备的上市,如何让手头上的APP适配多种机型多种屏幕尺寸变得尤为 ...
- 在 AutoLayout 和 Masonry 中使用动画
动画是 iOS 中非常重要的一部分,它给用户展现出应用灵气的一面. 在动画块中修改 Frame 在原来使用 frame 布局时,在 UIView 的 animate block 中对 view 的布局 ...
随机推荐
- PHP引用(&)的考察点
引用的概念 在PHP中引用意味着用不同的名字访问同一个变量内容. 定义方式 使用 & 符号来表示 变量的引用 $a = 'ABC'; //开辟一块内存空间存储数据,$a指向该空间 $b = & ...
- ThinkPHP---TP功能类之公文管理功能2----------继续完善
[前言] 之前已经完成了公文的添加和列表展示功能,今天继续完善.做下公文的编辑和删除功能. [主体] (1)分析 控制器:DocController.class.php 方法:edit(将模板展示和数 ...
- ThinkPHP---layer插件
[概论] (1)layer是基于jquery开发的一款美化弹框的插件,主要用于弹框效果的交互.但其他功能和组件也日益完善 官网:http://layer.layui.com 在线手册:http://w ...
- PHP下载压缩包文件
PHP 压缩文件需要用到 ZipArchive 类,Windows 环境需要打开 php_zip.dll扩展. 压缩文件 $zip = new ZipArchive(); // 打开一个zip文档,Z ...
- spark学习(1)---dataframe操作大全
一.dataframe操作大全 https://blog.csdn.net/dabokele/article/details/52802150 https://www.jianshu.com/p/00 ...
- replace、replaceAll、replaceFirst
replace.replaceAll.replaceFirst这三个函数会java的同学估计都用过,笔者已经用了2年多,可是,我们真的懂他们吗? 概述一下他们三个的用法: · replace(Char ...
- NOIP 2008 传纸条(洛谷P1006,动态规划递推,滚动数组)
题目链接:P1006 传纸条 PS:伤心,又想不出来,看了大神的题解 AC代码: #include<bits/stdc++.h> #define ll long long using na ...
- Cyclic Nacklace HDU - 3746 (kmp next数组应用)
题目大意 给出字符串,寻找最小要补全的字符个数,使得字符串是两次的循环 解法 通过寻找规律,我们又发现了len-next[len]又派上了用场 ①如果next[len]是0,说明最大前缀后缀和为0,那 ...
- [luogu3573 POI2014] RAJ-Rally (拓扑排序 权值线段树)
传送门 Solution 在DAG中我们可以\(O(n)\)预处理\(Ds(u)\)表示从u表示以s为起点的最长路\(Dt(u)\)表示以u为终点的最长路,那么经过\((u,v)\)的最长路即为\(D ...
- Python学习-字符串的基本知识
字符串的基本知识 根据所展示形式的不同,字符串也可以分为两类 原始字符串: 使用单引号包括:‘liuwen’ 使用双引号包括:"liuwen" 使用3个单引号包括 :'''liuw ...