用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:18.f] withLabelWidth:300]; self.subInfoHeight = [Model heightWithString:self.subInfo LabelFont:[UIFont systemFontOfSize:14.f] withLabelWidth:300]; self.detailsHeight = [Model heightWithString:self.details LabelFont:[UIFont italicSystemFontOfSize:16.f] withLabelWidth:300]; self.totalHeight = self.infoHeight + self.subInfoHeight + self.detailsHeight; return self; } #pragma mark - 计算文本高度 + (CGFloat)heightWithString:(NSString *)string LabelFont:(UIFont *)font withLabelWidth:(CGFloat)width { CGFloat height = 0; if (string.length == 0) { height = 0; } else { // 字体 NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:18.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(10, 10, 300, 20)]; _info.numberOfLines = 0; _info.font = [UIFont boldSystemFontOfSize:18.f]; _info.textColor = [UIColor blackColor]; [self addSubview:_info]; _subInfo = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 20)]; _subInfo.numberOfLines = 0; _subInfo.font = [UIFont systemFontOfSize:14.f]; _subInfo.textColor = [UIColor grayColor]; [self addSubview:_subInfo]; _details = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 20)]; _details.numberOfLines = 0; _details.font = [UIFont italicSystemFontOfSize:16.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(10, 10, 300, 20); [_info sizeToFit]; _subInfo.text = dataModel.subInfo; _subInfo.frame = CGRectMake(10, _info.height + 10, 300, 20); [_subInfo sizeToFit]; _details.text = dataModel.details; _details.frame = CGRectMake(10, _info.height + _subInfo.height + 10, 300, 20); [_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 / 2; } - (CGFloat)middleY { return self.height / 2; } @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 20 + model.totalHeight; } @end
一些需要注意的地方: