您的位置:首页 > 产品设计 > UI/UE

IOS 自定义 tableView cell(UITableViewCell height) 高度

2015-08-01 11:17 573 查看
IOS开发中,最常用的就是UITableView 了,这里,我做一个简单的帖子列表Demo,教大家用一种比较模块化的方法来自定义我们的cell 高度,废话不多说,我们开始新建一个工程。PS:采用纯代码的开发方式。 

运行截图:


 

步骤:新建一个singleViewApplication

步骤:通过新建group把工程目录结构改成如下图所示



通过上面的图片能够看得出来,工程包含了View层、Model层和ViewController层,是一个典型的MVC开发架构。

model层有一个帖子模型,包含三个属性。.m文件不需要做任何实现。

步骤:

核心代码是在cell里面,先贴上一段.h文件的代码:

#import <UIKit/UIKit.h>
#import "HQTieziModel.h"
#define hqTableViewCellIdentify @"HQ_TABLE_VIEW_CELL"

@interface HQTableViewCellData : NSObject
@property (nonatomic, assign) BOOL showBottomLine;
@property (nonatomic, assign) BOOL showTopLine;
@property (nonatomic, assign) float cellHeight;
@property (nonatomic, strong) HQTieziModel *tieziModel;

@property (nonatomic, assign) CGRect titleFrame;
@property (nonatomic, assign) CGRect descFrame;
@property (nonatomic, assign) CGRect photoFrame;

-(void)setUpCellData:(HQTieziModel *)tieziModel;

@end

@interface HQTableViewCell : UITableViewCell

@property (nonatomic, strong) HQTableViewCellData *cellData;

@end


看得出来,我这里是定义了另外一个类(HQTableViewCellData)来帮助设置cell的数据,在HQTableViewCellData里面通过一个方法来设置cellData的内容。并且定义了三个frame属性来存储计算出来的字符串和图片的frame.最后我们可以通过计算得到cellHeight并保存在cellData中。完整的实现过程在HQTableViewCellData.m文件里:

-(void)setUpCellData:(HQTieziModel *)tieziModel{
CGFloat originX = 15;
CGFloat originY = 15;

CGSize titleSize = [self boundingString:tieziModel.tieziTitle rectWithSize:CGSizeMake(ScreenWidth - 30, FLT_MAX) withStringFont:titleFont];

self.titleFrame = CGRectMake(originX, originY, titleSize.width, titleSize.height);
originY += titleSize.height;

CGSize descSize = [self boundingString:tieziModel.tieziDesc rectWithSize:CGSizeMake(ScreenWidth - 30, FLT_MAX) withStringFont:descFont];

self.descFrame = CGRectMake(originX, originY + 15, descSize.width, descSize.height);
originY += descSize.height + 15;

CGFloat pictureHeight = 80;
self.photoFrame = CGRectMake(originX, originY + 15 , pictureHeight, pictureHeight);
originY += pictureHeight + 15 + 10;

self.cellHeight = originY;
self.tieziModel = tieziModel;
}
//计算字符串高度方法
- (CGSize)boundingString:(NSString *)text rectWithSize:(CGSize)size withStringFont:(UIFont *)font{
NSDictionary *attribute = @{NSFontAttributeName: font};
CGSize retSize = [text boundingRectWithSize:size
options:\
NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:attribute
context:nil].size;
return retSize;
}


核心代码就是上面那段了,完整demo请戳这里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息