学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.

  1. Auto layout mode using "-systemLayoutSizeFittingSize:"
  2. 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+....);
}

本文demo点此下载,也能够前往github下载

AutoLayout初战----Masonry与FDTemplateLayoutCell实践的更多相关文章

  1. AutoLayout框架Masonry使用心得

    AutoLayout框架Masonry使用心得 字数1769 阅读1481 评论1 喜欢17 我们组分享会上分享了页面布局的一些写法,中途提到了AutoLayout,会后我决定将很久前挖的一个坑给填起 ...

  2. iOS开发通过代码方式使用AutoLayout (NSLayoutConstraint + Masonry)

    iOS开发通过代码方式使用AutoLayout (NSLayoutConstraint + Masonry) 随着iPhone6/6+设备的上市,如何让手头上的APP适配多种机型多种屏幕尺寸变得尤为迫 ...

  3. iOS AutoLayout自动布局&Masonry介绍与使用实践

    Masonry介绍与使用实践:快速上手Autolayout http://www.cnblogs.com/xiaofeixiang/p/5127825.html http://www.cocoachi ...

  4. Masonry和FDTemplateLayoutCell 结合使用示例Demo

    我们知道,界面布局可以用Storyboard或Xib结合Autolayout实现,如果用纯代码布局,比较热门的有Masonry.SDAutoLayout,下面的简单demo,采用纯代码布局,实现不定高 ...

  5. 【转】有趣的Autolayout示例-Masonry实现

    原文网址:http://tutuge.me/2015/05/23/autolayout-example-with-masonry/ 好久没有写Blog了,这段时间有点忙啊=.=本文举了3个比较有“特点 ...

  6. 代码方式使用AutoLayout (NSLayoutConstraint + Masonry)

    随着iPhone6/6+设备的上市,如何让手头上的APP适配多种机型多种屏幕尺寸变得尤为迫切和必要.(包括:iPhone4/4s,iPhone5/5s,iPhone6/6s,iPhone 6p/6ps ...

  7. iOS — Autolayout之Masonry解读

    前言 1 MagicNumber -> autoresizingMask -> autolayout 以上是纯手写代码所经历的关于页面布局的三个时期 在iphone1-iphone3gs时 ...

  8. IOS开发通过代码方式使用AutoLayout (NSLayoutConstraint + Masonry) 转载

    http://blog.csdn.net/he_jiabin/article/details/48677911 随着iPhone6/6+设备的上市,如何让手头上的APP适配多种机型多种屏幕尺寸变得尤为 ...

  9. 在 AutoLayout 和 Masonry 中使用动画

    动画是 iOS 中非常重要的一部分,它给用户展现出应用灵气的一面. 在动画块中修改 Frame 在原来使用 frame 布局时,在 UIView 的 animate block 中对 view 的布局 ...

随机推荐

  1. 项目经验——Sql server 数据库的备份和还原____还原数据库提示“介质集有2个介质簇,但只提供了1个。必须提供所有成员” .

    在对数据库备份与还原的过程中,我遇到一个问题“介质集有2个介质簇,但只提供了1个.必须提供所有成员”,下面详细的介绍一下遇到问题的经过与问题解决的方法! 一.备份与还原遇到的问题描述与解决方法: 前两 ...

  2. Angular——自定义过滤器

    基本介绍 除了使用AngularJS内建过滤器外,还可以根业务需要自定义过滤器,通过模块对象实例提供的filter方法自定义过滤器. 基本使用 (1)input是将绑定的数据以参数的形式传入 (2)i ...

  3. jquery插件集合

    jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多javascript高手加入其team. jQuery是继prototype之后又一个优秀的Javascrīpt框架.其经典 ...

  4. Java 基础入门随笔(8) JavaSE版——静态static

    面向对象(2) this:代表对象.代表哪个对象呢?当前对象. 当成员变量和局部变量重名,可以用关键字this来区分. this就是所在函数所属对象的引用.(简单说:哪个对象调用了this所在的函数, ...

  5. ThinkPHP---thinkphp控制器、路由、分组设置(C)

    配置文件分3类:系统配置文件,分组配置文件,应用配置文件 ①系统配置文件ThinkPHP/Conf/convention.php: ②分组 / 模块 /平台配置文件Home/Conf/config.p ...

  6. 新安装数据库sqlserver2008r2,使用javaweb连接不上问题处理

    鼠标右键[计算机]-->[管理],打开界面如下: 选择自己数据库的实例名: 选择TCP/IP:右键[属性],将所有TCP动态端口的[0]删掉,TCP端口设为1433:重启服务,即可连接. PS: ...

  7. Python之IO编程

    前言:由于程序和运行数据是在内存中驻留的,由CPU这个超快的计算核心来执行.当涉及到数据交换的地方,通常是磁盘.网络等,就需要IO接口.由于CPU和内存的速度远远高于外设的速度,那么在IO编程中就存在 ...

  8. LeetCode15——3Sum

    数组中找三个数和为0的结果集 1 // 解法一:先排序 然后固定一个值 然后用求两个数的和的方式 public static List<List<Integer>> three ...

  9. 让元素div消失在视野中

    让元素div消失在视野中1.position:absolute/relative/fixed + 方位 top/bottom/left/right: -9999px2.display:none3.vi ...

  10. [USACO] 打井 Watering Hole

    题目描述 Farmer John has decided to bring water to his N (1 <= N <= 300) pastures which are conven ...