-
- (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] autorelease];
-
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
-
label.tag = 1;
-
label.lineBreakMode = UILineBreakModeWordWrap;
-
label.highlightedTextColor = [UIColor whiteColor];
-
label.numberOfLines = 0;
-
label.opaque = NO;// 选中Opaque表示视图后面的任何内容都不应该绘制
-
label.backgroundColor = [UIColor clearColor];
-
[cell.contentView addSubview:label];
-
[label release];
-
}
-
-
UILabel *label = (UILabel *)[cell viewWithTag:1];
-
NSString *text;
-
text = [textArray objectAtIndex:indexPath.row];
-
CGRect cellFrame = [cell frame];
-
cellFrame.origin = CGPointMake(0, 0);
-
-
label.text = text;
-
CGRect rect = CGRectInset(cellFrame, 2, 2);
-
label.frame = rect;
-
[label sizeToFit];
-
if (label.frame.size.height > 46) {
-
cellFrame.size.height = 50 + label.frame.size.height - 46;
-
}
-
else {
-
cellFrame.size.height = 50;
-
}
-
[cell setFrame:cellFrame];
-
-
return cell;
-
}
-
-
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
-
{
-
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
-
return cell.frame.size.height;
-
}
-
还有一种方法就是添加一个专门用于计算cell高度的类
-
@interface DemoCell : NSObject{
UILabel *_content;
}
-(CGFloat)contentHeight;
-(void)setContent:(NSString *)content;
@end;
从上面的DemoCell来看其带有一个UILabel对象,这个Cell就是要根据UILabel的内容动态更改高度。其中contentHeight方法是返回Cell的高度。setContent是设置UILabel的内容并计算UILabel的高度。此类很简单要做的就是这样这些操作。然后我们在控制器中定义一个样本Cell专门用于计算Cell的高度。代码如下:
#import "DemoCell.h"
@interface DemoViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>{
UITableView *_tableView;
DemoCell *_sampleCell;
NSArray *_listData;
}
@end;
其中部分实现代码如下:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//在此使用样本Cell计算高度。
NSString *content=[_listData objectAtIndex:indexPath.row];
[_sampleCell setContent:content];
return [_sampleCell contentHeight];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellId=@"DemoCell";
DemoCell *cell=(DemoCell *)[tableView dequeueReusableCellWithIdentifier:cellId];
if(cell==nil){
cell=[[[DemoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
}
[cell setContent:[_listData objectAtIndex indexPath:indexPath.row]];
return cell;
}
到此为止我们已经顺利地展示了如何动态变更Cell的高度。只要内容变更我们调用UITableView的reloadData方法就可以刷新整个列表了。Cell如何计算高度本人没有列出来,因为不同的需求导致这部分的实现会不一样。这里只是把思路给大家交代清楚。具体的实现还是要各位童鞋们自己动手操作。