如何在开关部分中使用自定义类实例化UITableViewCell



我需要在cellForRowAtIndexPath的开头创建一个对象,以使用开关部分在其中添加不同的单元格:

switch (indexPath.section) {
    case DetailControllerAddressSection: {
        NSString *address = [self addressText];
        UITableViewCell *cell;
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            if (IS_OS_7_OR_LATER) {
                cell = (CustomDetailCell *) [tableView dequeueReusableCellWithIdentifier:@"AddressCell" forIndexPath:indexPath];
                cell.mainLabel.text = address;
                cell.detailLabel.text = [self distanceMessageForObjectData:self.objectData];
            } else {
                UniversalAddressCell *cell = (UniversalAddressCell *) [tableView dequeueReusableCellWithIdentifier:@"UniversalAddressCell" forIndexPath:indexPath];
                cell.backgroundView = [self cellBackgroundImageView:indexPath];
                cell.mainLabel.text = address;
...

但是在这种情况下,单元格是UITableViewCell,我无法从CustomDetailCell类中获取标签。如何解决这个问题?我相信这个决定很简单,但我不知道如何解决它。

问题在于这个:UITableViewCell *cell;

即使您将单元格转换为(CustomDetailCell *)存储类型仍UITableViewCell

您可以做的是:

switch (indexPath.section) {
case DetailControllerAddressSection: {
    NSString *address = [self addressText];
    UITableViewCell *cell;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        if (IS_OS_7_OR_LATER) {
            CustomDetailCell *detailCell = (CustomDetailCell *) [tableView dequeueReusableCellWithIdentifier:@"AddressCell" forIndexPath:indexPath];
            detailCell.mainLabel.text = address;
            detailCell.detailLabel.text = [self distanceMessageForObjectData:self.objectData];
            cell = detailCell;
        } else {
            UniversalAddressCell *universalCell = (UniversalAddressCell *) [tableView dequeueReusableCellWithIdentifier:@"UniversalAddressCell" forIndexPath:indexPath];
            universalCell.backgroundView = [self cellBackgroundImageView:indexPath];
            universalCell.mainLabel.text = address;
            cell = universalCell;

我想你会做类型转换。

[(CustomDetailCell *)cell mainLabel].text = address;

如果两个单元格有两个不同的 NIB:

static NSString *simpleTableIdentifier = @"SimpleTableCell";

SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
    switch (indexPath.section) {
        case DetailControllerAddressSection:
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell1" owner:self options:nil];
        cell1 = [nib objectAtIndex:0];
        // write here cell1 specific
        cell=cell1;
        break;
        case anotherCase:
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell2" owner:self options:nil];
        cell2 = [nib objectAtIndex:0];
        // write here cell2 specific
        cell=cell2;
    }
}

return cell;

最新更新