用Model来计算cell的高度

效果:

将计算cell高度的方法直接移植到Model当中,初始化的瞬间就计算好了高度,非常好用!

源码:

Model

//
// Model.h
//
// Copyright (c) 2014年 Y.X. All rights reserved.
// #import <Foundation/Foundation.h>
#import <UIKit/UIKit.h> @interface Model : NSObject @property (nonatomic, strong) NSString *info;
@property (nonatomic, strong) NSString *subInfo;
@property (nonatomic, strong) NSString *details; @property (nonatomic, assign) CGFloat infoHeight;
@property (nonatomic, assign) CGFloat subInfoHeight;
@property (nonatomic, assign) CGFloat detailsHeight;
@property (nonatomic, assign) CGFloat totalHeight; - (void)setValue:(id)value forUndefinedKey:(NSString *)key;
- (instancetype)initWithDictionary:(NSDictionary *)dictionary; @end
//
// Model.m
//
// Copyright (c) 2014年 Y.X. All rights reserved.
// #import "Model.h" @implementation Model - (void)setValue:(id)value forUndefinedKey:(NSString *)key { } - (void)setValue:(id)value forKey:(NSString *)key {
if ([value isKindOfClass:[NSNull class]]) {
return;
} [super setValue:value forKey:key];
} - (instancetype)initWithDictionary:(NSDictionary *)dictionary {
self = [super init];
if (self) {
if ([dictionary isKindOfClass:[NSDictionary class]]) {
[self setValuesForKeysWithDictionary:dictionary];
}
} self.infoHeight = [Model heightWithString:self.info LabelFont:[UIFont boldSystemFontOfSize:.f] withLabelWidth:];
self.subInfoHeight = [Model heightWithString:self.subInfo LabelFont:[UIFont systemFontOfSize:.f] withLabelWidth:];
self.detailsHeight = [Model heightWithString:self.details LabelFont:[UIFont italicSystemFontOfSize:.f] withLabelWidth:];
self.totalHeight = self.infoHeight + self.subInfoHeight + self.detailsHeight; return self;
} #pragma mark - 计算文本高度
+ (CGFloat)heightWithString:(NSString *)string LabelFont:(UIFont *)font withLabelWidth:(CGFloat)width {
CGFloat height = ; if (string.length == ) {
height = ;
} else { // 字体
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:.f]};
if (font) {
attribute = @{NSFontAttributeName: font};
} // 尺寸
CGSize retSize = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:
NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:attribute
context:nil].size; height = retSize.height;
} return height;
} @end

ModelCell

//
// ModelCell.h
// HeightModel
//
// Created by YouXianMing on 15/1/10.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
// #import <UIKit/UIKit.h> @interface ModelCell : UITableViewCell @property (nonatomic, strong) UILabel *info;
@property (nonatomic, strong) UILabel *subInfo;
@property (nonatomic, strong) UILabel *details; - (void)accessData:(id)model; @end
//
// ModelCell.m
// HeightModel
//
// Created by YouXianMing on 15/1/10.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
// #import "ModelCell.h"
#import "Model.h"
#import "UIView+SetRect.h" @implementation ModelCell - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { _info = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
_info.numberOfLines = ;
_info.font = [UIFont boldSystemFontOfSize:.f];
_info.textColor = [UIColor blackColor];
[self addSubview:_info]; _subInfo = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
_subInfo.numberOfLines = ;
_subInfo.font = [UIFont systemFontOfSize:.f];
_subInfo.textColor = [UIColor grayColor];
[self addSubview:_subInfo]; _details = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
_details.numberOfLines = ;
_details.font = [UIFont italicSystemFontOfSize:.f];
_details.textColor = [UIColor redColor];
[self addSubview:_details]; } return self;
} - (void)accessData:(id)model {
if ([model isKindOfClass:[Model class]]) {
Model *dataModel = model; _info.text = dataModel.info;
_info.frame = CGRectMake(, , , );
[_info sizeToFit]; _subInfo.text = dataModel.subInfo;
_subInfo.frame = CGRectMake(, _info.height + , , );
[_subInfo sizeToFit]; _details.text = dataModel.details;
_details.frame = CGRectMake(, _info.height + _subInfo.height + , , );
[_details sizeToFit];
}
} @end

工具类 UIView+SetRect

//
// UIView+SetRect.h
// TestPch
//
// Created by YouXianMing on 14-9-26.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import <UIKit/UIKit.h> @interface UIView (SetRect) // Frame
@property (nonatomic) CGPoint viewOrigin;
@property (nonatomic) CGSize viewSize; // Frame Origin
@property (nonatomic) CGFloat x;
@property (nonatomic) CGFloat y; // Frame Size
@property (nonatomic) CGFloat width;
@property (nonatomic) CGFloat height; // Frame Borders
@property (nonatomic) CGFloat top;
@property (nonatomic) CGFloat left;
@property (nonatomic) CGFloat bottom;
@property (nonatomic) CGFloat right; // Center Point
#if !IS_IOS_DEVICE
@property (nonatomic) CGPoint center;
#endif
@property (nonatomic) CGFloat centerX;
@property (nonatomic) CGFloat centerY; // Middle Point
@property (nonatomic, readonly) CGPoint middlePoint;
@property (nonatomic, readonly) CGFloat middleX;
@property (nonatomic, readonly) CGFloat middleY; @end
//
// UIView+SetRect.m
// TestPch
//
// Created by YouXianMing on 14-9-26.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "UIView+SetRect.h" @implementation UIView (SetRect) #pragma mark Frame - (CGPoint)viewOrigin
{
return self.frame.origin;
} - (void)setViewOrigin:(CGPoint)newOrigin
{
CGRect newFrame = self.frame;
newFrame.origin = newOrigin;
self.frame = newFrame;
} - (CGSize)viewSize
{
return self.frame.size;
} - (void)setViewSize:(CGSize)newSize
{
CGRect newFrame = self.frame;
newFrame.size = newSize;
self.frame = newFrame;
} #pragma mark Frame Origin - (CGFloat)x
{
return self.frame.origin.x;
} - (void)setX:(CGFloat)newX
{
CGRect newFrame = self.frame;
newFrame.origin.x = newX;
self.frame = newFrame;
} - (CGFloat)y
{
return self.frame.origin.y;
} - (void)setY:(CGFloat)newY
{
CGRect newFrame = self.frame;
newFrame.origin.y = newY;
self.frame = newFrame;
} #pragma mark Frame Size - (CGFloat)height
{
return self.frame.size.height;
} - (void)setHeight:(CGFloat)newHeight
{
CGRect newFrame = self.frame;
newFrame.size.height = newHeight;
self.frame = newFrame;
} - (CGFloat)width
{
return self.frame.size.width;
} - (void)setWidth:(CGFloat)newWidth
{
CGRect newFrame = self.frame;
newFrame.size.width = newWidth;
self.frame = newFrame;
} #pragma mark Frame Borders - (CGFloat)left
{
return self.x;
} - (void)setLeft:(CGFloat)left
{
self.x = left;
} - (CGFloat)right
{
return self.frame.origin.x + self.frame.size.width;
} - (void)setRight:(CGFloat)right
{
self.x = right - self.width;
} - (CGFloat)top
{
return self.y;
} - (void)setTop:(CGFloat)top
{
self.y = top;
} - (CGFloat)bottom
{
return self.frame.origin.y + self.frame.size.height;
} - (void)setBottom:(CGFloat)bottom
{
self.y = bottom - self.height;
} #pragma mark Center Point #if !IS_IOS_DEVICE
- (CGPoint)center
{
return CGPointMake(self.left + self.middleX, self.top + self.middleY);
} - (void)setCenter:(CGPoint)newCenter
{
self.left = newCenter.x - self.middleX;
self.top = newCenter.y - self.middleY;
}
#endif - (CGFloat)centerX
{
return self.center.x;
} - (void)setCenterX:(CGFloat)newCenterX
{
self.center = CGPointMake(newCenterX, self.center.y);
} - (CGFloat)centerY
{
return self.center.y;
} - (void)setCenterY:(CGFloat)newCenterY
{
self.center = CGPointMake(self.center.x, newCenterY);
} #pragma mark Middle Point - (CGPoint)middlePoint
{
return CGPointMake(self.middleX, self.middleY);
} - (CGFloat)middleX
{
return self.width / ;
} - (CGFloat)middleY
{
return self.height / ;
} @end

控制器

//
// ViewController.m
// HeightModel
//
// Created by YouXianMing on 15/1/10.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
// #import "ViewController.h"
#import "Model.h"
#import "ModelCell.h" static NSString *modelCellFlag = @"ModelCell.h"; @interface ViewController ()<UITableViewDataSource, UITableViewDelegate> @property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataModelArray; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; // 数据源
self.dataModelArray = [NSMutableArray array];
[self.dataModelArray addObject:[[Model alloc] initWithDictionary:@{@"info" : @"P.K.",
@"subInfo": @"逝者如斯,而未尝往也;盈虚者如彼,而卒莫消长也。盖将自其变者而观之,则天地曾不能以一瞬;自其不变者而观之,则物与我皆无尽也。",
@"details": @""}]];
[self.dataModelArray addObject:[[Model alloc] initWithDictionary:@{@"info" : @"YouXianMing",
@"subInfo": @"合抱之木,生于毫末;九层之合,起于垒土;千里之行,始于足下。",
@"details": @"精简计算UITableView文本高度"}]];
[self.dataModelArray addObject:[[Model alloc] initWithDictionary:@{@"info" : @"Q.L.",
@"subInfo": @"",
@"details": @""}]];
[self.dataModelArray addObject:[[Model alloc] initWithDictionary:@{@"info" : @"",
@"subInfo": @"",
@"details": @"This is a test ok ?"}]];
[self.dataModelArray addObject:[[Model alloc] initWithDictionary:@{@"info" : @"",
@"subInfo": @"YouXianMing 한 iOS 개발 엔지니어, 사랑 사랑 기술, 생활, 기꺼이 바치다, 좋아하는 게임만 좋아하는 것을 좋아하는 사람이다 가축, 학습, 확신하다 천도 보수 자주!",
@"details": @""}]];
[self.dataModelArray addObject:[[Model alloc] initWithDictionary:@{@"info" : @"遊賢明はiOS開発エンジニア、愛する技術で、生活を愛し、献身、ゲームが好き、好きなものを食べて、美食愛好家、天道酬勤を学ぶことが好きで、信じ!",
@"subInfo": @"",
@"details": @"YouXianMing copyright."}]];
[self.dataModelArray addObject:[[Model alloc] initWithDictionary:@{@"info" : @"ว่ายน้ำที่ชาญฉลาดเป็น iOS วิศวกรพัฒนาเทคโนโลยีและรักชีวิตรักและทุ่มเทและชอบเล่นเกมชอบกินอะไรดีเลยชอบการเรียนรู้และเชื่อว่าไม่มีอะไรเลย",
@"subInfo": @"Nager sage est un ingénieur, le développement de la technologie iOS amour, de l'amour de la vie, de dévouement, de jouer le jeu, aime manger, c'est un bon à rien, comme l'apprentissage, convaincu que Tiandaochouqin!",
@"details": @"entwickler, liebe, Leben, liebe, hingabe, Wie Spiele, der Gern Essen, ist ein Nahrungsmittel, Wie Lernen, Davon überzeugt, dass Gott"}]]; // tableView
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds
style:UITableViewStylePlain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.tableView registerClass:[ModelCell class] forCellReuseIdentifier:modelCellFlag];
[self.view addSubview:self.tableView]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataModelArray.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ModelCell *cell = [tableView dequeueReusableCellWithIdentifier:modelCellFlag];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell accessData:self.dataModelArray[indexPath.row]]; return cell;
} - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { Model *model = self.dataModelArray[indexPath.row];
return + model.totalHeight;
} @end

一些需要注意的地方:

用Model来计算cell的高度的更多相关文章

  1. iOS开发总结-UITableView 自定义cell和动态计算cell的高度

    UITableView cell自定义头文件:shopCell.h#import <UIKit/UIKit.h>@interface shopCell : UITableViewCell@ ...

  2. iOS不得姐项目--精华模块上拉下拉的注意事项,日期显示,重构子控制器,计算cell的高度(只计算一次),图片帖子的显示

    一.上拉下拉注意事项 使用MJRefresh中的上拉控件自动设置透明 当请求下页数据通过page的时候,注意的是上拉加载更多数据失败的问题,下拉加载数据失败了,页数应该还原.或者是请求成功的时候再将页 ...

  3. 基于Masonry自己主动计算cell的高度

    /** * This is a very very helpful category for NSTimer. * * @author huangyibiao * @email huangyibiao ...

  4. iOS UITextView 输入内容实时更新cell的高度

    iOS UITextView 输入内容实时更新cell的高度 2014-12-26 11:37 编辑: suiling 分类:iOS开发 来源:Vito Zhang'blog  11 4741 UIT ...

  5. 使用第三方UITableView+FDTemplateLayoutCell计算cell行高注意点

    现在很方便的计算单元格的行高大部分都是使用的第三方框架UITableView+FDTemplateLayoutCell,不知道你在使用这个框架的时候有没有遇到和我一样的问题,比如: 在这样计算cell ...

  6. 利用iOS8新特性计算cell的实际高度

    在计算cell的实际高度是 我们一般是通过计算frame  拿到最底部一个控件的最大Y值从而的到cell 的高度  算来算去  比较麻烦 其实,iOS8已经提供了直接通过Cell高度自适应的方法了,根 ...

  7. IOS8 不用计算Cell高度的TableView实现方案

    这个新特性,意味着View被Autolayout调整frame后,会自动拉伸和收缩SupView. 具体到Cell,要求cell.contentView的四条边都与内部元素有约束关系. 在TableV ...

  8. iOS开发之计算动态cell的高度并缓存

    项目中有个类似微博那样的动态cell,文字和图片的多少都不是确定的 刚开始使用autolayout,结果很多问题,最后我发现了一个框架 FDTemplateLayoutCell 写的很好,自动布局ce ...

  9. 1014-34-首页15-计算原创微博的frame------计算cell的高度---计算 UILabel 的 CGSize 的方法

    一.总体思路: 在控制器中,每次拿到数据模型(请求了数据.加载新微博)的时候,就调用 - (NSArray *)stausFramesWithStatuses:(NSArray *)statuses, ...

随机推荐

  1. 使用epublib解析epub文件(章节内容、书籍菜单)

    链接地址https://blog.csdn.net/sonnyching/article/details/47407549

  2. elasticsearch插件安装之--linux下安装及head插件

    /** * 系统环境: vm12 下的centos 7.2 * 当前安装版本: elasticsearch-2.4.0.tar.gz */ 安装和学习可参照官方文档: 1, 安装 # 下载, 获取不成 ...

  3. button按钮被输入法顶起来,遮盖了input输入框

    在做手机端的表单提交的时候,在chrome浏览器调试的时候,忘记输入法会引起布局的问题.在webApp里input输入框,会自动调起输入法,但是输入法会改变浏览器的可视区域的大小.就是会把浏览器可视区 ...

  4. GetHashCode方法学习

    GetHashCode方法我的理解是做两个对象的比较,每个对象,不管是值类型还是应用类型都提供这个基本函数,都可以去重写它.GetHashTable通常用于HashTable.List<> ...

  5. [转] 疯狂的JSONP

      何为跨域?何为JSONP?JSONP技术能实现什么?是否有必要使用JSONP技术? 跨域 就是由于JavaScript同源策略的限制,使得a.com域名下的js无法操作b.com或c.a.com域 ...

  6. Node.js学习笔记(七) --- Node.js的静态文件托管、路 由、EJS 模板引擎、GET 、POST

    1 . Nodejs 静态文件托管静态 web 服务器封装 2 . 路由 官方解释:  路由(Routing)是由一个 URI(或者叫路径)和一个特定的 HTTP 方法(GET.POST 等)组成的, ...

  7. JS获取地址栏参数&jquery

    第一种:字符串拆分法 window.location.href 或者 location.href 或者 window.location 获得地址栏中的所有内容 decodeURI()可以解码地址栏中的 ...

  8. c#之new关键词——隐藏基类方法

    当从基类继承了一个(非抽象成员时),也就继承了父类的实现代码.如果是virtual成员,可以override:另外一种方法也能隐藏父类的实现代码(虚成员和非虚成员都可使用):定义与父类相同的方法名,加 ...

  9. listview更改选中时item背景色(转)

    默认情况下使用ListView背景色是黑色,选中item的高亮颜色是菊黄色,很多时候不得不自己定义背景色或者背景图 android:cacheColorHint="@android:colo ...

  10. java运算符优先级别

    算数-->关系-->逻辑-->赋值