ios - tableView中的两种类型的单元格-优雅

标签 ios objective-c uitableview coding-style

您如何优雅编码同一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;

但是我的老师总是告诉我,如果在两种情况下都发生两次写错了,并且如您所见,这两种情况中的三行相同。我想将它们移至if之外,而只将每种情况下的特定行留在if主体中。

最佳答案

通过根据类型实例化单元格,但将单元格定义为UITableViewCell并在方法末尾返回实例,可以做得更好。这也将允许您为这些单元格可能共享的每个 public 属性只写一行。就像是:

UICustomTableViewCell *cell = nil; //This cell type is a common super class of both cell classes
NSDictionary *cellInfo = [_userInformation objectAtIndex:indexPath.row];
NSString *cellType = [cellInfo objectForKey:@"type"];
if ([cellType isEqualToString:kProfileImage]) {
    cell = [tableView dequeueReusableCellWithIdentifier:@"profileImageCell"];
}
else 
{
    cell = [tableView dequeueReusableCellWithIdentifier:@"AccountCell"];
    ((AccountCell*) cell).textField.placeholder = [cellInfo objectForKey:@"textFieldPlaceholder"];
    ((AccountCell*) cell).textField.delegate = self;
    ((AccountCell*) cell).textField.clearButtonMode = UITextFieldViewModeWhileEditing;
}
cell.delegate = self;
cell.descriptionLabel.text = [cellInfo objectForKey:@"cellLabelText"];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//Any other common properties can by assigned here

return cell;

在此示例中,两种单元格类型都有一个共同的“代理”属性。

关于ios - tableView中的两种类型的单元格-优雅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18736671/

相关文章:

iOS Afnetworking 2.0 AfSecurityPolicy.m 在构建项目时显示错误

php - 从 php 脚本返回数组到 Swift 时,JSON_encode 导致错误

javascript - Node.js AES 解密 iOS 加密的 NSString

ios - 进度 HUD 显示太晚

ios - UITableViewCell 在滚动时在某些单元格和不同的单元格中显示 UIImageView - 与 CoreData 和 NSFetchedResultsController 一起使用

ios - Xcode 服务 : Select Git Branch

防止 CRLF 的 iOS Base64 Lib

objective-c - 是否可以用 View 覆盖警报 View

ios - 更新 TableView 导致崩溃

ios - UITableView 不滚动,根据屏幕大小只显示 11 行