2014-06-20 52 views
0

我用下面的代碼添加一個UIButton到的UITableViewCell動態添加的UIButton到的UITableViewCell錯誤

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    MainCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
    cell = [[MainCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    self.btnMessage = [[UIButton alloc] initWithFrame:CGRectMake(20, 300, 54, 15)]; 
    [self.btnMessage setBackgroundImage:[UIImage imageNamed:@"message.png"] forState:UIControlStateNormal]; 
    [self.btnMessage addTarget:self action:@selector(messageButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.btnMessage setTitle:@"Message" forState:UIControlStateNormal]; 
    self.btnMessage.titleLabel.font = [UIFont systemFontOfSize:12.0f]; 
    [self.btnMessage setTitleEdgeInsets:UIEdgeInsetsMake(0, 12, 0, 0)]; 
    [cell addSubview:self.btnMessage]; 

    return cell; 
} 

一切正常,當我運行這段代碼,但如果我滾動表,按鈕會一次又一次地在添加每個單元格,如疊加或每個單元格都有一些相同的按鈕疊加,所以如何解決這個問題?

回答

3

移動代碼以添加if (cell == nil)語句中的按鈕。這將確保該按鈕僅添加到新單元格,而不是出列單元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    MainCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
    cell = [[MainCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

    self.btnMessage = [[UIButton alloc] initWithFrame:CGRectMake(20, 300, 54, 15)]; 
    [self.btnMessage setBackgroundImage:[UIImage imageNamed:@"message.png"] forState:UIControlStateNormal]; 
    [self.btnMessage addTarget:self action:@selector(messageButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.btnMessage setTitle:@"Message" forState:UIControlStateNormal]; 
    self.btnMessage.titleLabel.font = [UIFont systemFontOfSize:12.0f]; 
    [self.btnMessage setTitleEdgeInsets:UIEdgeInsetsMake(0, 12, 0, 0)]; 
    [cell addSubview:self.btnMessage]; 
    } 

    return cell; 
} 
相關問題