2012-01-16 86 views
2

如下圖所示,我在UITableViewCell中使用UIButton,可以選擇此按鈕,黃金星和未選中的灰色星。當選擇UITableViewCell時,UIButton會被覆蓋

enter image description here

的問題是,被選擇的小區不斷時,無論按鈕被選中或未被它會變成灰色(這灰色顏色比中的未選定模式的灰度顏色不同星)。我一直在試圖弄清楚爲什麼會發生這種情況,但沒有運氣。

enter image description here

這裏是細胞的實施,

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

UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];  
UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom]retain]; 

//set the background of the cells 
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed: @"cellBackground.png"]]; 
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cellselected2.png"]]; 

// set the button content 
[button setImage:[UIImage imageNamed:@"star.png" ] forState:UIControlStateNormal]; 
[button setImage:[UIImage imageNamed:@"starSelected.png"] forState:UIControlStateSelected]; 
[button addTarget:self action:@selector(selectedButton:) forControlEvents:UIControlEventTouchUpInside]; 
[button setFrame:CGRectMake(280, 10, 24, 24)]; 

[cell addSubview:button]; 

return cell; 
} 

還當我點擊該按鈕時,電池選擇按鈕將完全消失!

謝謝,

回答

6

我想通了什麼問題。問題是當選中單元格時,單元格中的UIButton將轉到「高亮狀態」。如果沒有指定用於按鈕按鈕高亮顯示狀態的圖像,它將看起來與我的情況相同。

於是我就加入了圖像,我想是對的UIButton使用高亮狀態,

[button setImage:[UIImage imageNamed:@"starSelected.png"] forState:UIControlStateHighlighted]; 

希望這有助於誰面臨着同樣的問題:)

+0

接受你自己的問題的答案沒關係。 – 2012-01-22 05:52:18

1

您正在添加按鈕到單元格框架,而不是它的contentView。

僅當選中單元格時,UITableViewCell纔會將此屬性的值作爲子視圖添加。它將選定的背景視圖作爲子視圖直接添加到背景視圖(backgroundView)的上方,如果它不是零,或者在所有其他視圖之後。 雖然UITableViewCell將背景視圖添加爲所有其他視圖背後的子視圖,並使用其當前幀位置。

更換

[cell addSubview:favButton]; 

[cell.contentView addSubview:favButton]; 

,並應解決這個問題。

UITableViewCell對象的內容視圖是單元格顯示內容的默認超級視圖。如果您想通過簡單地添加附加視圖來自定義單元格,則應該將它們添加到內容視圖中,以便在單元格進入和退出編輯模式時適當定位它們。

這一切都在AppleDocs ^^

編號:http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UITableViewCell_Class/Reference/Reference.html

+0

不幸的是,這並沒有解決它 – Mona 2012-01-16 09:26:31

+1

@Mona如果你添加[cell bringSubviewToFront:button];選擇後。或cell [cell sendSubviewToBack:cell.selectedBackground]; ? – 2012-01-16 09:33:14

+0

沒有工作。儘管如此,感謝 – Mona 2012-01-18 04:08:39

1

你其他人修好了當然可以設置突出顯示狀態的圖像。另一種選擇是,如果要爲UIControlStateNormalUIControlStateHighlighted使用相同的圖像,也可以說 button.adjustsImageWhenHighlighted = NO,默認值爲YES

+0

這不適合我。我沒有圖像(只是背景顏色),當單元格被選中時,按鈕也被選中。我也將這些按鈕添加到contentView – Darren 2015-03-20 03:13:57