2014-11-04 23 views
0

我創建了一個帶有星形圖片的按鈕,點擊時需要更改圖片。就像點擊按鈕使收藏夾,然後再次點擊刪除收藏夾。我需要製作一個最喜歡的按鈕,並在點擊時更改圖片

這裏的代碼

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; 


if (cell == nil) 
{ 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
            reuseIdentifier:@"Cell"]; 

} 
favButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[favButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
[favButton setBackgroundImage:[UIImage imageNamed:@"stardes.png"] forState:UIControlStateNormal]; 
favButton.frame = CGRectMake(200, 90, 20, 25); 
[cell.contentView addSubview:favButton]; 

return cell; 
} 
+0

將它的圖像設置爲buttonClicked中的新圖像? – CW0007007 2014-11-04 14:16:24

+1

,但這個問題不會起作用,因爲當單元格重繪時,它會再次使用原始圖像重繪。您需要保留一份「最喜歡的」索引路徑,並根據該索引路徑是否被「收錄」來佈局單元格選擇和圖像時, – CW0007007 2014-11-04 14:17:39

回答

0

你必須保存狀態的地方。它通常存儲在由indexPath索引的數組(yourdataset)中,我注意到你不使用它。除了點擊更改圖像之外,您還需要設置陣列中的狀態。 在buttonClicked方法中,迭代superView,直到到達單擊按鈕的UITableViewCell,找到表中的位置。現在您可以更改數組中的數據索引。

之後,只需檢查設置背景圖像之前的狀態。就像這樣:

MyData* dta = self.myData[ indexPath.row ]; 
if (dta.favorite) 
    [favButton setBackgroundImage:[UIImage imageNamed:@"stardes.png"] forState:UIControlStateNormal]; 
else 
    [favButton setBackgroundImage:[UIImage imageNamed:@"stardes2.png"] forState:UIControlStateNormal];