您的位置:首页 > 移动开发 > IOS开发

iOS TableViewCell 动态调整高度

2015-10-13 14:20 423 查看
在写sina 微博的显示微博内容时,用到cell进行显示,那么就要考虑到不同微博内容导致的cell高度问题。在微博显示的内容中包括了文字和图片,那么就要计算文字部分的高度和图片部分的高度。这篇博文就记录一下如何处理cell高度的动态调整问题吧!

一、传统的方法

在tableview的delegate的设置高度的方法中进行设置- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath,当然在这个代理方法中需要计算文字的高度以及图片的高度,然后返回。

1、文字(string)高度的处理;

由于文字的长度的不确定的,所以就要根据这个动态的文字长度来计算机显示文字的的高度

[cpp] view
plaincopy

#define FONT_SIZE 14.0f

#define CELL_CONTENT_WIDTH 320.0f

#define CELL_CONTENT_MARGIN 10.0f

NSString *string = @"要显示的文字内容";

CGSize size = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAXFLOAT);

CGSize textSize = [string sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];

以上代码就是计算文字高度。其中size是装载文字的容器,其中的height设置为maxfloat;然后用方法

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode

Returns the size of the string if it were rendered with the specified constraints.就可以知道string的size了

2、图片高度的处理;

首先你先要下载到图片,然后CGSize imageViewSize = CGSizeMake(image.size.width,image.size.height);就可以获取到图片的size,就可以对你的imageview的frame进行设置了,那么也就知道了图片的高度了。

二、非传统方法

在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath代理方法中处理cell的frame的高度,在tableview的delegate的设置高度的方法中调用这个方法,那么就可以得到设置好的cell高度。(注意到二者方法的执行顺序:heightForRowAtIndexPath这个代理方法是先执行的,后执行cellForRowAtIndexPath)

[cpp] view
plaincopy

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

//cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];

//这个方法已经 Deprecated

cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];

}

CGRect cellFrame = [cell frame];

cellFrame.origin = CGPointMake(0, 0);

//获取cell的高度的处理

cellFrame.size.height = ***;

[cell setFrame:cellFrame];

return cell;

}

稍微解释一下,注意到cell初始化的时候是CGRectZero,然后[cell frame]获取cell的frame,让后就可以对cell的高度进行处理后,setFrame 重新设置cell 的frame了。

接下来就是在heightForRowAtIndexPath这个方法中调用。

[cpp] view
plaincopy

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];

return cell.frame.size.height;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: