我理解在所有 if/for/while 方法都像这样运行之后返回值的值(value):
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int rowHeight = 0;
if (tableView == secondTable) {
rowHeight = 62;
}
if (tableView == thirdTable) {
rowHeight = 72;
}
return rowHeight;
}
但是我可以声明什么样的变量能够承载不同的结果...在这种情况下,UITableViewCell 的两个不同的自定义类:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// some variable here?
if (tableView == secondTable) {
static NSString *MyIdentifier = @"MyIdentifier";
CustomCell2 *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[CustomCell2 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
return cell; //don't return yet
}
if (tableView == thirdTable) {
static NSString *MyIdentifier = @"MyIdentifier";
CustomCell3 *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[CustomCell3 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
return cell; //don't return yet
}
// Ideally would return a UITableViewCell here to avoid "control may reach end of non-void function"
}
最佳答案
不能保证 tableView
始终是 secondTable
或 thirdTable
,因此在其他情况下最好返回一个空单元格。有一个空单元格总比没有返回任何东西而崩溃要好。
它应该是这样的:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
if (tableView == secondTable) {
static NSString *MyIdentifier = @"MyIdentifier";
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = (UITableViewCell *)[[CustomCell2 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
} else if (tableView == thirdTable) {
static NSString *MyIdentifier = @"MyIdentifier";
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = (UITableViewCell *)[[CustomCell3 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
} else {
// init an empty cell of some kind
// cell = ...
}
return cell;
}
使用此方法使用从自定义类到父类(super class) UITableViewCell 的向下转换。
请注意,您必须显式转换以避免编译时警告。
如果您打算添加更多自定义单元格,请将 if 语句替换为开关。
关于ios - 如何返回两个唯一值之一并避免 "Control may reach end of non-void function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37148498/