读书人

怎么动态设置UITableView的RowHeight

发布时间: 2013-01-01 14:04:19 作者: rapoo

如何动态设置UITableView的RowHeight ???
我给每行的cell添加一个uiimageview,
这个uiimageview使用sdwebimage加载网络上的图片。
现在想动态设置tableview每行的高度为对应加载图片的高度。
但是在获取cell里的uiimageview对象时报错。



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIImageView * img=(UIImageView * )[[tableView cellForRowAtIndexPath:indexPath].subviews objectAtIndex:0];
return img.frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}

//图片的url地址
NSString * str=[[[dataArr objectAtIndex:indexPath.row] objectForKey:@"file"] objectForKey:@"key"];

UIImageView * img1=[[UIImageView alloc] initWithFrame:CGRectMake(100, 0, 192, 100)];
[img1 setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:ImgUrl,str]]];
[cell addSubview:img1];
[img1 release];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.layer.borderColor=[UIColor blackColor].CGColor;
cell.layer.borderWidth=2;
return cell;
}

[解决办法]
如果你想动态地生成高度,你就必须在获取内容的时候就已经计算出每一个CELL的高度;你可以将生成的内容画在cell的contentView上,然后计算contentView的高度,然后放到一个数组里,这样在这个方法里- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath,就可以通过indexPath去获取每一个cell的高度了。

至于你为什么会出错,是你还没有搞清楚UITableView的各方法的调用顺序,tableView:cellForRowAtIndexPath 是在tableView:heightForRowAtIndexPath之后的,你还没有生出来,怎么可能先说话?所以出错了。

你去把苹果的UITableView文档多研究一下,google一下别人的解说也行。

SO。。没了。

[解决办法]
图片加载完毕之后:
[tableview beginUpdates];
[tableview endUpdates];
这个时候,tableview会再次循环cell的高度,这个时候你就应该能返回正确的高度了。
[解决办法]
你直接把你的需要cell里显示的content,在cellForRowAtIndexPath之前,在heightForRowAtIndexPath里算出来。  
   类似: 数据数组array,在heightForRowAtIndexPath里,把array的每一行拿出来算高度。再在cellForRowAtIndexPath里去填充数据!

读书人网 >Iphone

热点推荐