ios - 无法从我声明它的 'if' block 之后返回变量

标签 ios objective-c c

我在 cellForRowAtIndexPath 中有以下内容,但它无法编译,因为 cell 的范围仅限于 if 语句。正确的写法是什么?

int val=indexPath.row % 2;
if(val==0) {
    TRCell *cell = (TRCell*)[tableView dequeueReusableCellWithIdentifier:@"myCell"];
    cell.topLabel.text = @"whatever";
    cell.subLabel.text = @"down below";
} else {
    TROddCell *cell = (TROddCell*)[tableView dequeueReusableCellWithIdentifier:@"cell2"];
    cell.subLabel.text = @"down below in sub";
}

return cell;

最佳答案

你有两个选择:

1) 将 return 语句保留在原来的位置,但在 if 语句之前声明 cell,以便它与您的return声明。

int val=indexPath.row % 2;
UITableViewCell *cell;
if(val==0){
    TRCell *trCell = (TRCell*)[tableView dequeueReusableCellWithIdentifier:@"myCell"];
    trCell.topLabel.text = @"whatever";
    trCell.subLabel.text = @"down below";
    cell = trCell;
} else{
    TROddCell *trOddCell = (TROddCell*)[tableView dequeueReusableCellWithIdentifier:@"cell2"];
    trOddCell.subLabel.text = @"down below in sub";
    cell = trOddCell;
}

return cell;

2) 从定义单元格的范围返回cell

int val=indexPath.row % 2;
if(val==0){
    TRCell *cell = (TRCell*)[tableView dequeueReusableCellWithIdentifier:@"myCell"];
    cell.topLabel.text = @"whatever";
    cell.subLabel.text = @"down below";
    return cell;
} else{
    TROddCell *cell = (TROddCell*)[tableView dequeueReusableCellWithIdentifier:@"cell2"];
    cell.subLabel.text = @"down below in sub";
    return cell;
}

关于ios - 无法从我声明它的 'if' block 之后返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18040766/

相关文章:

ios - NSUrlConnection 执行多次

ios - Swift 4 旋转回跳

ios - 使用侧边栏菜单时,UITableView 无意中向下移动了 ~1 英寸

objective-c - 删除期间自定义单元格中的自动调整标签大小

使用 1 和 0 的序列创建我自己的数据类型

c - 为函数参数指定寄存器?

ios - 单击其他按钮顶部的“禁用”按钮会触发另一个按钮的单击事件

ios - 核心位置不请求用户许可

Objective-C:在循环中从 NSString 中删除尾随逗号

c - 代码中的这一行是什么意思? (指向字符的指针数组)?