2011-06-05 113 views
1

我很難更改包含在表格視圖單元格中的我的UIButton的圖像。我的代碼如下:按下按鈕更改單元格內的UIButton圖像

// In tableview for cell at rowIndex method 
self.iconBtn = [[UIButton alloc]initWithFrame:CGRectMake(670,10,80, 80)]; 
      self.iconBtn.tag = kIconValueTag; 

[cell.contentView addSubview:self.iconBtn]; 

//Add icon to cell 
UIImage *btnImage = [UIImage imageNamed:@"blank_star.png"]; 

[self.iconBtn setImage:btnImage forState:UIControlStateNormal]; 

// I am calling method changeIconState after user clicks on icon. 
[self.iconBtn addTarget:self action:@selector(changeIconState) forControlEvents:UIControlEventTouchUpInside]; 

後,表視圖的方法之外的方法被稱爲:

-(void)changeIconState 
{ 
    if (self.iconSelectState == kIconNotSelected) 
    { 
     self.iconSelectState = kIconSelected; 
    } 
    else 
    { 
     self.iconSelectState = kIconNotSelected; 
    } 
    [self changeIcon]; 

} 
-(void)changeIcon 
{ 
    if (self.iconSelectState == kIconSelected) 
    { 
     UIImage *btnImageHighlighted = [UIImage imageNamed:@"star.png"]; 
     [self.iconBtn setImage:btnImageHighlighted forState:UIControlStateNormal]; 
    } 
    else 
    { 
     UIImage *btnImageNormal = [UIImage imageNamed:@"blank_star.png"]; 
     [self.iconBtn setImage:btnImageNormal forState:UIControlStateNormal]; 
    } 

} 

我運行該程序後,圖標沒有從空白變成明星如我所願。它只是一個空白的明星。我在這裏錯過了什麼嗎?

+2

可能是一個邏輯問題 - 如果不測試代碼,可以在不同情況下設置一些NSLog或斷點,並查看它在哪裏結束。 – Luke 2011-06-05 11:15:24

+0

而這個按鈕只在一個單元格中? – 2011-06-05 11:21:13

+0

iconSelectState的初始值是什麼? – Tatvamasi 2011-06-05 11:21:16

回答

1

你爲什麼要自己管理圖像/按鈕狀態?爲什麼不將兩個圖像加載到已定義的狀態並讓操作系統處理它?

//Add icon to cell 
UIImage *btnImage = [UIImage imageNamed:@"blank_star.png"]; 
UIImage *btnImageHighlighted = [UIImage imageNamed:@"star.png"]; 

[self.iconBtn setImage:btnImage forState:UIControlStateNormal]; 
[self.iconBtn setImage:btnImageHighlighted forState:(UIControlStateHighlighted && UIControlStateSelected)]; 

如果你需要管理你的財產(iconSelectedState),你可以不用擔心形象。或者,您可以查詢按鈕狀態屬性以確定它處於哪個狀態。

相關問題