如何使用动态重用标识符设置和出列自定义UITableViewCell?

问题描述 投票:3回答:2

这是我最终要做的事情。我想在UITableView中显示项目菜单,但是要动态显示,以便显示的项目类型决定加载的自定义单元格视图。例如,假设菜单项类型为'switch',那么它将加载一个名为'switch.xib'的笔尖,状态将根据特定菜单项的值开启/关闭。可能有5个项目是“切换”类型,但值不同。所以我想为每个使用相同的xib,但是5个实例。

所以,很长一段时间的问题。当我从笔尖加载单元格视图时,我认为当它在屏幕上滚动时,它需要唯一的重用标识符,对吧? (每个实例都是唯一的,即每个菜单项。)在Interface Builder的UITableViewCell中,我看到我可以在哪里设置重用标识符属性,但我想在运行时为每个交换机实例设置它。例如,菜单项#1是交换机,#2是文本字段,#3是交换机等。因此#1和#3都需要唯一的小区ID才能出列。

这是我的cellForRowAtIndexPath的样子:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Cells are unique; dequeue individual cells not generic cell formats
NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d", indexPath.row];

ITMenuItem *menuItem = [menu.menuItems objectAtIndex:indexPath.row];

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    // Load cell view from nib
    NSString *cellNib = [NSString stringWithFormat:@"MenuCell_%@", menuItem.type];
    [[NSBundle mainBundle] loadNibNamed:cellNib owner:self options:nil];
    cell = myCell;
    self.myCell = nil;
}
// Display menu item contents in cell
UILabel *cellLabel = (UILabel *) [cell viewWithTag:1];
[cellLabel setText:menuItem.name];
if ([menuItem.type isEqualToString:@"switch"]) {
    UISwitch *cellSwitch = (UISwitch *) [cell viewWithTag:2];
    [cellSwitch setOn:[menuItem.value isEqualToString:@"YES"]];
}
else if ([menuItem.type isEqualToString:@"text"]) {
    UITextField *textField = (UITextField *) [cell viewWithTag:2];
    [textField setText:menuItem.value];
}

return cell;
}
ios uitableview nib
2个回答
0
投票

您可以在nib文件中设置重用标识符。因此,对于switch.xib,您可以使用“switch”作为重用标识符。然后改变

NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d", indexPath.row];

NSString *CellIdentifier = menuItem.type;

假设menuItem.type是'开关'


0
投票
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell == nil)
    {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    TextFieldFormElement *item = [self.formItems objectAtIndex:indexPath.row];
    cell.labelField.text = item.label;
    return cell;
}
© www.soinside.com 2019 - 2024. All rights reserved.