博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AutoLayout初战----Masonry与FDTemplateLayoutCell实践
阅读量:6657 次
发布时间:2019-06-25

本文共 7773 字,大约阅读时间需要 25 分钟。

          学iOS也有几个月了。一直都是纯代码开发,菜鸟入门,到今天还处在Frame时代。刚好近期项目在提审。有点时间能够学学传说中的AutoLayout。事实上。就是android的相对布局(RelativeLayout),没了解之前一直认为非常神奇,今天学习了一下,才发现AutoLayout也不是那么神奇不可触碰.

          在frame时代,一切数据在我们手中都是一个个坐标,我们所要做的,就是用数据反推控件的大小,然后显示出来。只是,自从i6出了之后,屏幕的宽度也不再是固定的了。AutoLayout是大势所趋。

          在AutoLayout时代,我们不须要用数据去反推控件大小。而是我们给控件加入约束,告诉控件。你该在大概哪个地方,比方,距离SuperVIew的左边20个点,距离SuperView的上边10个点,接触过android开发的人应该会对这个概念比較熟悉。然后系统帮我们自己主动计算出frame。

          近期也研究过用Storyboard为控件加约束。相对于纯代码来说简单非常多,只是,还是怕多人开发出现故障,还是用了纯代码来实现了。

          如题。这次我是使用了来完毕AutoLayout,这里有一篇关于Masonry的介绍,这个开源项目已经帮我们将iOS比較复杂的AutoLayout封装起来,使用起来也比較方便。

能够帮助我们计算cell的高度而且缓存起来,使用也是很方便。关于FDTemplateLayoutCell的介绍能够看这篇文章:。

          本篇文章所用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 ()
{ 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; *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="=" 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]; addview:_titlelabel]; _contentlabel="[[UILabel" _contentlabel.numberoflines="0;" _contentlabel.font="[UIFont" systemfontofsize:14]; _contentlabel.textcolor="[UIColor" graycolor]; _contentlabel.backgroundcolor="[UIColor" purplecolor]; addview:_contentlabel]; _mainimageview="[[UIImageView" _mainimageview.contentmode="UIViewContentModeScaleAspectFill;" _mainimageview.clipstobounds="YES;" _mainimageview.backgroundcolor="[UIColor" orangecolor]; addview:_mainimageview]; _usernamelabel="[[UILabel" _usernamelabel.backgroundcolor="[UIColor" greencolor]; _usernamelabel.textcolor="[UIColor" _usernamelabel.font="[UIFont" systemfontofsize:12]; addview:_usernamelabel]; _timelabel="[[UILabel" _timelabel.textcolor="[UIColor" bluecolor]; _timelabel.font="[UIFont" _timelabel.backgroundcolor="[UIColor" 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 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 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 make.top.equalto(_mainimageview.mas_bottom).prioritylow(); constraint_usernamelabel="make.top.equalTo(_mainImageView.mas_bottom).offset(5).priorityHigh();" [_timelabel make.top.equalto(_usernamelabel.mas_top); make.bottom.equalto(self.contentview.mas_bottom).offset(-margin); }];}- (void)setselected:(bool)selected animated:(bool)animated setselected:selected animated:animated]; configure the view for 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 ,也能够前往 下载

转载地址:http://ftqto.baihongyu.com/

你可能感兴趣的文章
direct path read等待事件
查看>>
ecshop提交到服务器,样式不正确
查看>>
splunk日志监控利器
查看>>
spring入门概念
查看>>
Linux三剑客之grep
查看>>
shell readarray命令
查看>>
linux系统运维企业常见面试题集合(一)
查看>>
Linux文本查看命令之tail
查看>>
python的lxml模块
查看>>
centos7.x搭建gitlab9.2.2
查看>>
CentOS 7 如何设置默认启动方式为命令行模式
查看>>
haproxy+keepalived+mycat+mysql (读写分离)
查看>>
对PostgreSQL的UPDATE和DELETE外键属性思考
查看>>
day10-linux查找find命令 介绍
查看>>
Netbeans 8.1启动参数配置
查看>>
PostgreSQL9.6 服务器参数配置
查看>>
eclipse maven添加本地仓库的jar包
查看>>
Linux基础知识题解答(二)
查看>>
Scenario 4 – HP C7000 Virtual Connect flexFabric SUS with Active/Active
查看>>
Linux(RHEL7及CentOS7)下DNS服务器的搭建与配置
查看>>