2013-11-09 81 views
0

我使用此代碼來更改我的UITableView中的UIButton。 問題是當我滾動表的按鈕正在改變沒有任何理由。在定製單元格中更改UIButton

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
[button setFrame:CGRectMake(232, 88, 78, 24)]; 

if([[array objectAtIndex:(indexPath.row)] isEqualToString:@"0"]) 
    [button setImage:[UIImage imageNamed:@"pic1"] forState:UIControlStateNormal]; 
else 
    [button setImage:[UIImage imageNamed:@"pic2"] forState:UIControlStateNormal]; 

[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
[Cell.contentView addSubview:button]; 

這是buttonClicked:方法:

-(void)buttonClicked:(id)sender 
{ 
    CGPoint touchPoint = [sender convertPoint:CGPointZero toView:self.myTableView]; 
    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:touchPoint]; 
    UIButton *button = (UIButton *)sender; 
    if([[array objectAtIndex:indexPath.row] isEqualToString:@"0"]) 
    { 
     [button setImage:[UIImage imageNamed:@"pic2"] forState:UIControlStateNormal]; 
     [array replaceObjectAtIndex:indexPath.row withObject:@"1"]; 
    } 
    else 
    { 
     [button setImage:[UIImage imageNamed:@"pic1"] forState:UIControlStateNormal]; 
     [array replaceObjectAtIndex:indexPath.row withObject:@"0"]; 
    } 
} 
+0

這是因爲表視圖重用它的單元格,你應該在委託方法'tableview:cellforrowatindexpath:'更新你的按鈕的狀態或任何其他按鈕的屬性。 –

回答

1

那是因爲你的被重用。試試這個:

UIButton *button; = (UIButton *) [cell viewWithTag:34]; 
if (!button) { 
button = [UIButton buttonWithType:UIButtonTypeCustom]; 
[button setFrame:CGRectMake(232, 88, 78, 24)]; 
button.tag = 34; 

if([[array objectAtIndex:(indexPath.row)] isEqualToString:@"0"]) 
    [button setImage:[UIImage imageNamed:@"pic1"] forState:UIControlStateNormal]; 
else 
    [button setImage:[UIImage imageNamed:@"pic2"] forState:UIControlStateNormal]; 

[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
[Cell.contentView addSubview:button]; 
} 
+0

仍然無法正常工作,我按下按鈕1,向下滾動,按鈕5和按鈕6變爲圖片2。向上滾動,button1變回pic1。 – user2755038

+0

我犯了一個錯字,再次嘗試代碼:) – 7c9d6b001a87e497d6b96fbd4c6fdf

+0

對不起,仍然是同樣的問題。 – user2755038

相關問題