-1

私は次のものを持っていますが、ifステートメントにスコープが設定されているため、cellForRowAtIndexPathコンパイルされません。cellこれはどう書くのが正しいのでしょうか?

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

3 に答える 3

3

次の 2 つの選択肢があります。

1)ステートメントをそのままにしておきますが、ステートメントの前にreturn宣言して、ステートメントと同じスコープ内にあるようにします。cellifreturn

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;
}
于 2013-08-04T13:31:59.700 に答える
1

if ブロック内からセルを返すこともできます。

ところで、セルが他の点で等しい場合は、色を動的に設定し、同じセル サブクラスを使用する方がエレガントです。

cell.contentView.backgroundColor = indexPath.row % 2 ?
   kLightCellBackgroundColor : kDarkCellBackgroundColor;
于 2013-08-04T07:37:04.523 に答える