用Model来计算cell的高度
用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的高度的更多相关文章
- iOS开发总结-UITableView 自定义cell和动态计算cell的高度
UITableView cell自定义头文件:shopCell.h#import <UIKit/UIKit.h>@interface shopCell : UITableViewCell@ ...
- iOS不得姐项目--精华模块上拉下拉的注意事项,日期显示,重构子控制器,计算cell的高度(只计算一次),图片帖子的显示
一.上拉下拉注意事项 使用MJRefresh中的上拉控件自动设置透明 当请求下页数据通过page的时候,注意的是上拉加载更多数据失败的问题,下拉加载数据失败了,页数应该还原.或者是请求成功的时候再将页 ...
- 基于Masonry自己主动计算cell的高度
/** * This is a very very helpful category for NSTimer. * * @author huangyibiao * @email huangyibiao ...
- iOS UITextView 输入内容实时更新cell的高度
iOS UITextView 输入内容实时更新cell的高度 2014-12-26 11:37 编辑: suiling 分类:iOS开发 来源:Vito Zhang'blog 11 4741 UIT ...
- 使用第三方UITableView+FDTemplateLayoutCell计算cell行高注意点
现在很方便的计算单元格的行高大部分都是使用的第三方框架UITableView+FDTemplateLayoutCell,不知道你在使用这个框架的时候有没有遇到和我一样的问题,比如: 在这样计算cell ...
- 利用iOS8新特性计算cell的实际高度
在计算cell的实际高度是 我们一般是通过计算frame 拿到最底部一个控件的最大Y值从而的到cell 的高度 算来算去 比较麻烦 其实,iOS8已经提供了直接通过Cell高度自适应的方法了,根 ...
- IOS8 不用计算Cell高度的TableView实现方案
这个新特性,意味着View被Autolayout调整frame后,会自动拉伸和收缩SupView. 具体到Cell,要求cell.contentView的四条边都与内部元素有约束关系. 在TableV ...
- iOS开发之计算动态cell的高度并缓存
项目中有个类似微博那样的动态cell,文字和图片的多少都不是确定的 刚开始使用autolayout,结果很多问题,最后我发现了一个框架 FDTemplateLayoutCell 写的很好,自动布局ce ...
- 1014-34-首页15-计算原创微博的frame------计算cell的高度---计算 UILabel 的 CGSize 的方法
一.总体思路: 在控制器中,每次拿到数据模型(请求了数据.加载新微博)的时候,就调用 - (NSArray *)stausFramesWithStatuses:(NSArray *)statuses, ...
随机推荐
- php使用date()函数时,提示的警告
转载:http://www.shangxueba.com/jingyan/121682.html 在用PHP5.3以上的PHP版本时,只要是涉及时间的会报一个: "PHP Warning: ...
- printf()函数中\t,水平制表符,空格的个数
在控制台输出数据的时候,也就是用printf()的时候,我们经常用\t来控制对齐,以使输出的结果更加整齐美观. 然而有时候我们发现及时使用了\t 也会出现数据对不齐的情况,这就跟\t究竟对应几个空格有 ...
- kafka-2.11-0.11集群搭建
kafka集群依赖于zookeeper,所以需要先搭建zookeeper集群,kafka默认自带了内建的zookeeper,建议使用自己外搭建的zookeeper,这样比较灵活并且解耦服务,同时也可以 ...
- [Hive]使用 Antlr 开发领域语言
Antlr 简介 ANTLR 语言识别的一个工具 (ANother Tool for Language Recognition ) 是一种语言工具,它提供了一个框架,可以通过包含 Java, C++, ...
- jQuery.on() 函数
1.绑定所有的<p>元素// 为所有P元素分别绑定click事件处理函数handler$("p").on("click", handler); 2. ...
- C#.NET下转换泛型列表为JSON格式
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Te ...
- linq之多表连接
1.左连接: var LeftJoin = from emp in ListOfEmployees join dept in ListOfDepartment on emp.DeptID equals ...
- Oracle安装后遇到错误:The Network Adapter could not establish the connection
http://note.youdao.com/noteshare?id=e6baee7ea7b7f60d7a265124e2bdd46c&sub=988945C6DDE843D5A7D6588 ...
- 设置navigationbar透明度时的坑
1.需要设置导航条透明度时 UIImage *image = [UIImage imageNamed:@"bg_clear.png"]; //设置背景颜色 [nav2.na ...
- 532 -数组中的K-diff对
例1: 输入: [3,1,4,1,5],k = 2 输出: 2 说明:阵列中有两个2-diff对,(1,3)和(3,5). 虽然我们在输入中有两个1,但我们应该只返回唯一对的数量. 例2: 输入: ...