我创建了一个名为 TestTableViewCell 的 tableViewCell 子类。我已经使用它连接了数据源和委托(delegate)。问题是它似乎没有做我在子类中所说的任何事情,甚至没有改变背景?
self.tableView.delegate = self;
self.tableView.datasource = self;
我已将单元格类更改为 TestTableViewCell 并创建了一个名为 Cell 的标识符。
cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[TestTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
return cell;
}
子类
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
UIButton *btn1 = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.frame) - 60, 10, 50, 30)];
[btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn1 setTitle:@"B1" forState:UIControlStateNormal];
[self.contentView addSubview:btn1];
UIButton *btn2 = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(btn1.frame), 70, 50, 30)];
[btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn2 setTitle:@"B2" forState:UIControlStateNormal];
[self.contentView addSubview:btn2];
UIButton *btn3 = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(btn1.frame), 130, 50, 30)];
[btn3 setTitle:@"B3" forState:UIControlStateNormal];
[btn3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.contentView addSubview:btn3];
UISwipeGestureRecognizer *gesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(moveCover:)];
gesture.direction = UISwipeGestureRecognizerDirectionLeft;
UISwipeGestureRecognizer *gesture2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(moveCover:)];
gesture2.direction = UISwipeGestureRecognizerDirectionRight;
_coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 5, CGRectGetWidth(self.frame), 195)];
_coverView.backgroundColor = [UIColor grayColor];
[self.contentView addSubview:_coverView];
[self addGestureRecognizer:gesture];
[self addGestureRecognizer:gesture2];
self.selectionStyle = UITableViewCellSelectionStyleNone;
}
return self;
}
最佳答案
假设您正在使用 Interface Builder 并拥有一个带有“自定义”动态原型(prototype)单元格的 UITableView。您是否将 TestTableViewCell 子类分配给 IB 中的表格单元格行(就像您在创建自定义 UITableViewController 子类时为 UITableViewController 所做的那样?如果您不这样做,那么当您将单元格出列时,您将获得单元格(和默认类) 在 IB 中定义,而不是带有自定义类的自定义单元格。
另外,请注意,子类中的所有按钮创建逻辑等都可以直接进入 IB 中的自定义单元格(视觉上),并且如果您选择的话,可以避免所有这些代码。只需在 IB 中直观地设计行,然后使用助理编辑器在自定义单元 (TestTableViewCell) header 和实现 (.m) 中创建导出和操作。
最后,您不需要在 CellForRowAtIndexPath 中分配单元格
关于ios - customTableViewCell 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25140132/