您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

客製化 UITableView 的點擊與高亮背景色

編輯:iOS 技巧大全

系統預設的選取高亮是一層灰底,有些設計稿會要求換成品牌色或干脆不要。這件事比想像中容易踩坑,原因在於 UITableViewCell 的層級結構。

做法一:覆寫 setSelected:

- (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,再自行決定要在哪個環節上色——這條路徑比跟系統預設行為纏鬥省事得多。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved