點擊UITableViewCell發生了什么?

EstWheatley 7年前發布 | 8K 次閱讀 iOS開發 移動開發 UITableViewCell

今天遇到一個有關 UITableViewCell 的奇怪現象。

我的 UITableViewCell 上有一個 subview ,是用來顯示未讀數的。我給這個 subview 設置了一個紅色背景,就像這樣:

未選擇cell時

但是我選中這個cell時,發現未讀數的背景色沒有了,只有數字,就像這樣:

選擇cell時

借此機會我了解到我們通常點擊一個 UITableViewCell 時發生了哪些事,我按照調用方法的順序繪制了一個簡單的流程圖:

點擊UITableViewCell的調用方法

可以看到,手指按下的時候,Cell就進入 highlighted 狀態。其實,Cell的 subview 也同時進入了 highlighted 狀態。這個時候,Cell會把所有所有 subview 的背景色清空,以便設置統一的背景色。一般有如下幾種選中模式:

UITableViewCellSelectionStyleNone,

UITableViewCellSelectionStyleBlue,

UITableViewCellSelectionStyleGray,

UITableViewCellSelectionStyleDefault

解決辦法

我們可以選擇UITableViewCellSelectionStyleNone,背景色就不會修改的。但是顯然不能滿足我們的應用場景。

正如Apple開發文檔說的:

A custom table cell may override this method to make any transitory appearance changes.

我們重載 (void)setSelected:(BOOL)selected animated:(BOOL)animated 和 (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated 方法,在這里面我們來設置 subview 的背景色。

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];
    _unreadBadge.backgroundColor = [UIColor redColor];
}

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {

    [super setHighlighted:highlighted animated:animated];
    _unreadBadge.backgroundColor = [UIColor redColor];
}

這樣既可以按照系統的選擇風格來,又可以自定義 subview 背景色,perfect!

 

來自:http://www.jianshu.com/p/903ef14f269b

 

 本文由用戶 EstWheatley 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!