2

我有一个习惯UITableViewCell。我想访问单元格属性,即 aUILabel等。我尝试插入以下代码:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CategorieCell *customCell = (CategorieCell *)[tableView cellForRowAtIndexPath:indexPath];

    return ...
}

当我运行该应用程序时,它崩溃了,但没有提供错误详细信息。问题出在我正在创建的新 customCell 上。还有其他方法可以访问customCell.m对象吗?

4

3 回答 3

2

关于崩溃,请注意您使用的是 cellForRowAtIndexPath: wich 是您必须实现的 UITableViewDatasource 中的方法,该方法默认调用 heightForRowAtIndexPath ,因此它将成为递归

我假设您希望在此方法中使用自定义单元格,以便从中获取高度。实现这一点的最佳方法是在 CategorieCell 上编写一个类方法,为您提供具有特定数据的单元格的高度。

其他选项是使用代码提取方法以获取 uitableviewcell,例如

(CategorieCell*) categorieCellForIndex:(NSIndex)index selected:(BOOL)selected{
...
}
于 2015-02-05T22:25:33.287 回答
1

heightForRowAtIndexPath永远不应该调用in cellForRowAtIndexPath

第一个在第二个之前调用,如果您需要访问标签(例如计算文本的高度),您通常可以初始化一个单元格。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static CategorieCell *cell;
    if (!cell) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
        cell.frame = CGRectMake(0, 0, tableView.frame.size.width-tableView.contentInset.left-tableView.contentInset.right, cell.frame.size.height);
        [cell layoutIfNeeded];
    }

    cell.label.text = myDatasourceText;

    CGFloat cellHeight = ....

    return cellHeight;
}

注意 1:dequeueReusableCellWithIdentifier假设您使用的是 Interface Builder,否则您需要使用alloc] initWithStyle:...];

注意 2: 如您所见,我正在设置单元格的框架。这是必需的,否则您的单元格将(320 x 44)作为默认值。相反,您可能在 iniPhone 6/6+ (i.e. screen width: 414)或 in 中iPad,您可能需要根据标签的宽度和文本计算标签的高度,因此您需要设置单元格的框架。

注意 3: 我假设您有一组相等的单元格结构,因此我正在使用一个static单元格,因此它将被重用而不分配其他无用的单元格。

于 2015-02-05T22:27:27.200 回答
1

尝试像这样注册您的自定义单元类:

[self.tableView registerClass:[CategorieCell class] forCellReuseIdentifier:NSStringFromClass([CategorieCell class]);

然后在-tableView:heightForRowAtIndexPath:做类似的事情:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{    
    CategorieCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CategorieCell class)];

}
于 2015-02-05T22:27:51.410 回答