我在 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/