2016-11-08 74 views
0

我有一個自定義單元格的tableview控制器。對於每種類型的細胞,我都在故事板和課堂上創建了一個原型細胞。Tableview和自定義單元格不可預知的行爲

這裏的小區中的一個:

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(故事板中的默認值),有時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 
+0

這是因爲重新使用單元格,您需要添加完整的'cellForRowAtIndexPath'方法。 –

+0

cellForRowAtIndexPath的else部分在哪裏?你確定那個單元格的行號是0嗎? – Windindi

回答

0

kaushal的建議做到了訣竅!

而不是設置標題是這樣的:

[cell.milestoneNumber.titleLabel setText:@"2"] 

我所做的:

[cell.milestoneNumber setTitle:@"2" forState:UIControlStateNormal]; 

而現在它的工作就好了。雖然我不確定爲什麼。

0

我想你應該設置你的awakeFromNib按鈕的默認階段。 在您的自定義表格視圖單元格類:

- (void)awakeFromNib 
{ 
    // Initialization code 
    [super awakeFromNib]; 

    self.milestoneNumber.titleLabel.text = @""; 
} 
1

問題是與可重用性,所以這裏最好的解決辦法是重新像這樣prepareForReuse方法標籤:

- (void)prepareForReuse { 
    [super prepareForReuse]; 
    [self.milestoneNumber setTitle:@"" forState:UIControlStateNormal]; 
} 

而且在配置電池,設置標題如:

[self.milestoneNumber setTitle:@"2" forState:UIControlStateNormal]; 
+1

更新按鈕文本使用:self.milestoneNumber.titleLabel.textAlignment = NSTextAlignmentCenter; [button setTitle:@「2」forState:UIControlStateNormal]; – kaushal

+0

謝謝。我嘗試過,但沒有奏效。 –

+0

謝謝kaushal!你的解決方案工作 –

相關問題