【发布时间】:2013-09-11 08:51:52
【问题描述】:
您将如何优雅地在同一个 tableView 中编写两种类型的单元格?
显然我可以这样做:
NSDictionary *cellInfo = [_userInformation objectAtIndex:indexPath.row];
NSString *cellType = [cellInfo objectForKey:@"type"];
if ([cellType isEqualToString:kProfileImage]) {
ProfileImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"profileImageCell"];
cell.descriptionLabel.text = [cellInfo objectForKey:@"cellLabelText"];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
else {
AccountCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AccountCell"];
cell.descriptionLabel.text = [cellInfo objectForKey:@"cellLabelText"];
cell.textField.placeholder = [cellInfo objectForKey:@"textFieldPlaceholder"];
cell.textField.delegate = self;
cell.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
return nil;
但是我的老师总是告诉我不要写两次,如果它在两种情况下都发生,并且如你所见,两种情况下有 3 行是相同的。我想将它们移到 if 之外,并且只在 if 正文中保留针对每种情况的特定行。
【问题讨论】:
-
下面的答案很好,但在我看来,虽然你不应该“写两次”你这样做的方式完全没问题。
标签: ios objective-c uitableview coding-style