簡體   English   中英

UITableViewCell selectedBackgroundView 不起作用

[英]UITableViewCell selectedBackgroundView does not work

我的 UITableViewCells 都是預定義的“字幕”樣式。 我想將選定單元格的背景圖像設置為另一張圖片。 我嘗試了各種方法來實現這一點,並且在 stackoverflow 上討論的所有方法似乎都失敗了。 我再次嘗試了一些其他更簡單的方法來更改 selectedBackgroundView 屬性,例如:

cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.bounds] ;
cell.selectedBackgroundView.backgroundColor = [UIColor yellowColor];

但它也不起作用。 那有什么問題?

據我了解,您想將選定的背景圖像設置為您的單元格?

cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"backgroundImage.png"]];

編輯:

據我所知,在這種常見情況下,選擇后UITableViewCell無法突出顯示:

  1. 在某處設置cell.selectionStyle = UITableViewCellSelectionStyleNone;
  2. 您實現willSelectRowAtIndexPath並返回nil
  3. 有設置[self.tableView setAllowsSelection:NO];
  4. 可能是你設置self.tableView.userInteractionEnabled = NO ; cell.userInteractionEnabled = NO
  5. 您將 UITableViewCell 子類化並實現了不正確的方法setSelected:animated:setHighlighted:animated

可能會分享您的cellForRowAtIndexPath方法代碼來調查問題

您可以通過多種方式更改突出顯示顏色。

更改單元格的selectionStyle屬性。 如果將其更改為UITableViewCellSelectionStyleGray ,它將是灰色的。

您還可以在tableView:didSelectRowAtIndexPath:

//do something like this for color
cell.selectionStyle= UITableViewCellSelectionStyleGray;

// for image
cell.selectedBackgroundView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"imageName"]];

更改selectedBackgroundView屬性。 實際上,創建藍色漸變的是視圖。 您可以創建一個視圖並繪制您喜歡的任何內容,並將該視圖用作表格視圖單元格的背景。

祝你好運。。

在我的情況下,在 Xcode 13 - sdk iOS 15+ 上編譯后出現了問題,並對代碼進行了任何更改。 最終我將單元格子類化並添加代碼:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{   
    [super setSelected:selected animated:animated];
    
    [self.contentView insertSubview:self.selectedBackgroundView
    atIndex:0];
    
    self.selectedBackgroundView.hidden = !selected;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM