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

时间:2013-08-04 07:32:25

标签: 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;

3 个答案:

答案 0 :(得分:3)

您有两种选择:

1)将return语句保留在原来的位置,但在cell语句之前声明if,以使其与return语句的范围相同。< / p>

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;
}

答案 1 :(得分:1)

您也可以从if块中返回单元格。

顺便说一下,如果细胞相等,那么动态设置颜色并使用相同的细胞亚类会更优雅。

cell.contentView.backgroundColor = indexPath.row % 2 ?
   kLightCellBackgroundColor : kDarkCellBackgroundColor;

答案 2 :(得分:1)

简单,正如你所说,这是一个范围问题。只需将退货拉出并将其添加到每个if语句中。

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;
}