系統預設的選取高亮是一層灰底,有些設計稿會要求換成品牌色或干脆不要。這件事比想像中容易踩坑,原因在於 UITableViewCell 的層級結構。
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
if (selected) {
self.backgroundColor = [UIColor redColor];
} else {
self.backgroundColor = [UIColor whiteColor];
}
}
如果你試了發現沒生效,打開 Xcode 的 View Debugger 看階層就明白了:系統的高亮 view 蓋在你的 cell 上面,你把 cell 底色塗成紅色,自然被遮住了。
解法是在初始化 cell 之後補上一行:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
這樣系統就不再產生那層高亮 view,你的背景色終於能露出來。
若希望點擊時 briefly 變色後立刻恢復,可以用 tableView 的代理方法處理高亮事件。先在 cell 中把兩個狀態都設為白色:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
self.backgroundColor = [UIColor whiteColor];
}
再於代理中響應 didHighlightRowAtIndexPath:
- (void)tableView:(UITableView *)tableView
didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.backgroundColor = [UIColor greenColor];
}
手指放開後,系統會回到 selected 狀態,而 setSelected: 又把它設回白色,視覺上就形成「閃一下」的效果。
上述邏輯都可以收攏進自訂 cell 裡,不必散落在外部:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
[super setHighlighted:highlighted animated:animated];
if (highlighted) {
self.backgroundColor = [UIColor redColor];
} else {
self.backgroundColor = [UIColor whiteColor];
}
}
最後提醒一個常見困惑:直接改 cell.contentView.backgroundColor 往往看不到效果,因為系統的高亮 view 就在 contentView 之上。想穩定控制高亮外觀,記得把 selectionStyle 設為 None,再自行決定要在哪個環節上色——這條路徑比跟系統預設行為纏鬥省事得多。