ios - Tableview 和自定义单元格不可预测的行为

标签 ios objective-c uitableview

我有一个带有自定义单元格的 TableView Controller 。对于每种类型的单元格,我在 Storyboard中创建了一个原型(prototype)单元格以及一个类。

这是其中一个单元格:

enter image description here

单元格有一个包含数字的圆形按钮。

我正在尝试修改我的 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(这是我想要的)。

enter image description here

这是我的 (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/

相关文章:

ios - leftbarbuttonitem脱离框架

ios - 委托(delegate)给另一个 View Controller 不起作用

swift - 立即重新加载 TableView (Parse + Swift)

ios - EXC_BAD_ACCESS UITable 在 numberOfRowsInSection 中设置 tableHeaderView

ios - 获取使用 Logic 生成的 midi 序列 (MusicSequence) 标记

objective-c - [NSDate distancePant] 返回的错误指针

ios - 自定义 CIKernel 和 iOS7

ios - 将 Apple DateCell 示例转换为使用 UIPickerView 而不是 UIDatePickerView

快速在 UITableView 中异步加载图像 - 顶部单元格没有图片

iphone - 一行中的多个单元格