0

这适用于我的普通样式表视图,但不适用于我的分组样式。我正在尝试自定义单元格在被选中时的外观。

这是我的代码:

+ (void)customizeBackgroundForSelectedCell:(UITableViewCell *)cell {
    UIImage *image = [UIImage imageNamed:@"ipad-list-item-selected.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    cell.selectedBackgroundView = imageView;
}

我已经验证了正确的单元格确实被传递到了这个函数中。我需要做些什么不同的事情才能完成这项工作?

4

1 回答 1

1

从您的问题中不清楚您是否知道 tableViewCell 根据其选择状态自动管理显示/隐藏它的 selectedBackgroundView 。除了 in 之外,还有更好的地方可以放置该方法viewWillAppear。一种是在您最初创建 tableViewCells 时,即:

- (UITableViewCell *)tableView:(UITV*)tv cellForRowAtIP:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    cell = [tv dequeueCellWithIdentifier:@"SomeIdentifier"];
    if (cell == nil) {
        cell = /* alloc init the cell with the right reuse identifier*/;
        [SomeClass customizeBackgroundForSelectedCell:cell];
    }
    return cell;
}

您只需在该单元格的生命周期中设置一次selectedBackgroundView 属性。单元格将在适当时管理显示/隐藏它。

另一种更简洁的技术是将 UITableViewCell 子类化,并在子类的 .m 文件中覆盖:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithBla....];
    if (self) {
        UIImageView *selectedBGImageView = /* create your selected image view */;
        self.selectedBackgroundView = selectedBGImageView;
    }
    return self;
}

从那时起,您的单元格应显示其自定义选择的背景,无需任何进一步修改。它只是工作。

viewDidLoad:此外,此方法更适用于当前推荐的使用以下 UITableView 方法向表格视图注册表格视图单元格类的做法:

- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier

您将在表格视图控制器的viewDidLoad方法中使用此方法,以便您的表格视图单元出列实现更短且更易于阅读:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[SomeClass class]
           forCellReuseIdentifier:@"Blah"];
}

- (UITableViewCell *)tableView:(UITV*)tv cellForRowAtIP:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    cell = [tableView dequeueReusableCellWithIdentifier:@"Blah"
                                           forIndexPath:indexPath];
    /* set your cell properties */
    return cell;
 }

只要您使用@"Blah"标识符注册了一个类,此方法就保证返回一个单元格。

于 2013-07-15T00:29:50.067 回答