用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, ...
随机推荐
- docker容器网络通信原理分析(转)
概述 自从docker容器出现以来,容器的网络通信就一直是大家关注的焦点,也是生产环境的迫切需求.而容器的网络通信又可以分为两大方面:单主机容器上的相互通信和跨主机的容器相互通信.而本文将分别针对这两 ...
- SpringMVC异常处理机制
SpringMVC异常处理机制 springMVC会将所有在doDispatch方法中的异常捕获,然后处理.无法处理的异常会抛出给容器处理. 在doDispatch()中调用processDispat ...
- OOAD之创建型模式之工厂模式
首先我们为什么要学习设计模式呢? 1)模式从经验中总结出来的,经过证实的方案,模式只有在实际系统中经过多次验证之后才能成为模式. 2) 提高系统的可维护性, 通过使用设计模式,在系统面临升级和维护时, ...
- jqGrid随窗口大小变化自适应大小-转
第一种: jqGrid随窗口大小变化自适应宽度 $(function(){ $(window).resize(function(){ $("#listId").setGridWid ...
- elasticsearch分析系列
http://www.opscoder.info/category/ElasticSearch/?page=2 https://www.jianshu.com/p/0908b9ee65fc https ...
- 【LeetCode题解】160_相交链表
目录 160_相交链表 描述 解法一:哈希表 思路 Java 实现 Python 实现 解法二:双指针(推荐) 思路 Java 实现 Python 实现 160_相交链表 描述 编写一个程序,找到两个 ...
- 产环境部署node记录(三): centOS 7 mySQL和mongoDB的安装
[mySQL的安装]: CentOS7默认数据库是mariadb,现在来安装mySQL 1.下载安装包 这里下载了四个安装包,后面会用到 yum -y install perl perl-devel ...
- Socket编程 - 网络基础知识
API编程部分:http://www.cnblogs.com/Jimmy1988/p/7895213.html 1. 协议简介 此处,我们主要介绍Linux编程常用的三种协议(TCP/UDP/IP), ...
- Angular的第一个helloworld
在安装了node,npm,angular-cli,vscode之后,我们来创建一个angular的应用 创建第一个hello world 使用的IDE工具为vscode 打开vscode,打开一个命令 ...
- 番外篇 之 Win32Api
C# 调用系统API. 从自己的软件,来操作别人写好的软件. SendMessage 句柄 标识当前进程/控件的一个标识; 本课程所用到的常量信息: private const uint LB_FI ...