gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:19:03 30 4
gpt4 key购买 nike

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

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com