我有一个带有自定义单元格的 TableView Controller 。对于每种类型的单元格,我在 Storyboard中创建了一个原型(prototype)单元格以及一个类。
这是其中一个单元格:
单元格有一个包含数字的圆形按钮。
我正在尝试修改我的 cellForRowAtIndexPath 方法中的数字值,如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
TrackMilstoneCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"TrackMilstoneCell"];
if (cell == nil) {
cell = [[TrackMilstoneCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TrackMilstoneCell"];
}
cell.backgroundColor = cell.contentView.backgroundColor;
cell.milestoneNumber.backgroundColor = UIColorFromRGB(0xA875E1);
[cell.milestoneNumber.titleLabel setText:@"2"];
return cell;
} ...
但是,我的行为非常不可预测。每次重新加载 tableview 时,我有时会得到 1( Storyboard 中的默认值),有时会得到 2(这是我想要的)。
这是我的 (TrackMilstoneCell) 类的代码:
#import "TrackMilstoneCell.h"
@implementation TrackMilstoneCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
-(void)layoutSubviews
{
[self viewSetup];
}
-(void)viewSetup
{
self.milestoneNumber.layer.masksToBounds = NO;
self.milestoneNumber.layer.borderColor = [UIColor whiteColor].CGColor;
self.milestoneNumber.layer.borderWidth = 4;
self.milestoneNumber.layer.cornerRadius = self.milestoneNumber.bounds.size.width / 2.0;
}
- (void)awakeFromNib
{
// Initialization code
[super awakeFromNib];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
最佳答案
问题在于可重用性,所以这里最好的解决方案是像这样在 prepareForReuse 方法中重置标签:
- (void)prepareForReuse {
[super prepareForReuse];
[self.milestoneNumber setTitle:@"" forState:UIControlStateNormal];
}
在配置单元格时,设置标题如下:
[self.milestoneNumber setTitle:@"2" forState:UIControlStateNormal];
关于ios - Tableview 和自定义单元格不可预测的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40479585/