在cellForRowAtIndexPath中,当单元格是可变高度时获取单元格的高度

时间:2012-08-21 21:19:12

标签: iphone ios

我在tableview中创建自定义单元格,有些图像很高,有些只是文本。单元格的高度是在heightForRowAtIndexPath中计算的,我在调用cellForRowAtIndexPath之前完成了。我想在单元格底部放置一个imageview而不管高度,但我不知道如何从cellForRowAtIndexPath中获取计算出的高度?

3 个答案:

答案 0 :(得分:15)

答案太迟了..

但是,就像@ user216661指出的那样,获取Cell或ContentView的高度的问题是它返回单元格的原始高度。包含可变高度的行,这是一个问题。

更好的解决方案是获取单元格的矩形(rectForRowAtIndexPath),然后从中获取高度。

- (UITableViewCell *)tableView:(UITableView *)iTableView cellForRowAtIndexPath:(NSIndexPath *)iIndexPath {
    UITableViewCell *aCell = (UITableViewCell *)[iTableView dequeueReusableCellWithIdentifier:aCellIdentifier];
    if (aCell == nil) {
        CGFloat aHeight = [iTableView rectForRowAtIndexPath:iIndexPath].size.height;
        // Use Height as per your requirement.
    }

    return aCell;
}

答案 1 :(得分:3)

你可以询问代表,但是你会问两次,因为tableView已经相应地询问和调整了单元格。最好从细胞本身中找出......

// in cellForRowAtIndexPath:, deque or create UITableViewCell *cell
// this makes the call to heightForRow... and sizes the cell
CGFloat cellHeight = cell.contentView.bounds.size.height;

// alter the imageView y position (assuming the rest of the frame is correct)
CGRect imageFrame = myImageView.frame;
imageFrame.y = cellHeight - imageFrame.size.height;   // place the bottom edge against the cell bottom
myImageView.frame = imageFrame;

答案 2 :(得分:-1)

您可以自己调用heightForRowAtIndexPath!只需从cellForRowAtIndexPath传递indexPath作为参数,您就可以知道要设置的单元格的高度。

假设您正在使用UITableViewController,只需在cellForRowAtIndexPath中使用它......

float height = [self heightForRowAtIndexPath:indexPath]
相关问题