需要在UITableView的heightForRowAtIndexPath中访问我的UITableViewCell类:

时间:2014-04-05 00:57:09

标签: ios objective-c uitableview

我需要根据我的UITextView高度设置UITableViewCell高度,但是当我使用CommentTableViewCell *cell = (CommentTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];中的heightForRowAtIndexPath:访问单元格sublcass时,app会崩溃。

怎么了?这不是访问我的自定义单元类的正确方法吗?

2 个答案:

答案 0 :(得分:0)

如果UITextView高度取决于运行时之前未知的某些字符串长度,那么您应该遵循MVC架构并确定某个模型对象中定义的该字符串的高度。您可以使用NSString sizeWithFont或sizeWithAttributes方法来获取文本大小。

答案 1 :(得分:0)

根据我的经验,heightForRowAtIndexPath会在显示单元格之前自动触发。因此,您需要在显示之前知道单元格的高度。你无法在heightForRowAtIndexPath中执行此操作,似乎您认为可以在heightForRowAtIndexPath期间查看单元格文本的高度来更改它。

您需要做的是创建一个数组并存储高度。然后,您现在可以使用该数组并在heightForRowAtIndexPath中提取数字。

以下是一个例子:

- (void) calculateHeight {
UILabel *tempTitle = [[UILabel alloc] init];
tempTitle.font = [UIFont fontWithName:@"your font" size:@"size"];
tempTitle.lineBreakMode = NSLineBreakByWordWrapping;


for (int i = 0; i < [yourListOfData count]; i++) {

    NSString *yourText = [yourListOfData objectAtIndex:i];

    CGSize textSize = [yourText
                   sizeWithFont:@"size"
                   constrainedToSize:CGSizeMake(0, "maxsize of your label that you want")
                   lineBreakMode:NSLineBreakByWordWrapping];


    [listOfHeightPerItem addObject:[NSNumber numberWithFloat:(textSize.height + 20)]];
    //+20 for padding
    }
}

然后在你的heightForRowAtIndexPath:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat tempHeight = [(NSNumber *)[listOfHeightPerItem objectAtIndex:indexPath.row] floatValue];
    return tempHeight;
}

请注意,这不是最佳方式,但它有效......特别是当你的截止日期是昨天;)