如何在委托方法之外访问tableview单元格?

时间:2016-06-30 21:14:06

标签: ios objective-c uitableview

我有一个包含2种原型单元格的表格。第一个细胞充当静电池。在'didselect'其他行的方法(从1到结束),我只需要在第1个单元格中添加一个组件。然后应根据其中的内容增加第一个单元的高度。我的想法是试图增加细胞高度,

- (CGFloat)tableView: (UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *)indexPath {
     if(indexPath.row == 0){

        TagTableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathWithIndex:0]];
        return [cell.tagView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize].height + 1;
     }else {
         return 75;
     }
}

但我无法访问该单元格。我得到了一个糟糕的请求。这是一种方便的方法吗?还是有其他方法吗?建议我。

1 个答案:

答案 0 :(得分:0)

实现上述功能的另一种简单方法(使用全局NSString * firstRowText,这有助于在运行时随时从变量中获取文本,而不是获取单元格,然后从中获取文本):

NSString *firstRowText = @"";

细胞高度:

 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        if(indexPath.row==0) {
            return [self heightForTextViewRectWithWidth:tableView.frame.size.width andText:firstRowText];
        }
        return 20;
    }

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSIndexPath *firstCellIndex = [NSIndexPath indexPathForRow:0 inSection:0];

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:firstCellIndex];
    firstRowText = [firstRowText stringByAppendingString:@"String to appened everytime on didSelectRow"];
    [cell.textLabel setText:firstRowText];

    [tableView reloadRowsAtIndexPaths:@[firstCellIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
}

引自How to resize UITableViewCell to fit its content?

-(CGFloat)heightForTextViewRectWithWidth:(CGFloat)width andText:(NSString *)text
{
    UIFont * font = [UIFont systemFontOfSize:12.0f];

    // this returns us the size of the text for a rect but assumes 0, 0 origin
    CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: font}];

    // so we calculate the area
    CGFloat area = size.height * size.width;

    CGFloat buffer = 5.0f;

    // and then return the new height which is the area divided by the width
    // Basically area = h * w
    // area / width = h
    // for w we use the width of the actual text view
    return floor(area/width) + buffer;
}