日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Swift自定義UITableViewCell背景色_Swift

作者:Hierarch_Lee ? 更新時間: 2022-04-07 編程語言

本文實例為大家分享了Swift自定義UITableViewCell背景色的具體代碼,供大家參考,具體內容如下

效果

前言

前段時間在整理課件 《UITableView》 章節的時候,看著單元格選中時的背景顏色覺得特別扭,系統給的顏色太過單調,當時想整理一篇修改單元格選中樣式的文章,但一直沒有時間,現在閑下來,終于可以完成了。在實際開發中,系統提供的樣式不能滿足需求,可能大家想到的最直接的方式就是定制,自定義。沒錯,這里修改表格視圖單元格選中時的背景顏色也是通過自定義單元格的方法實現,當然也可以通過代理方法實現,如果有興趣,大家可以研究一下。

實現

在UITableViewCell的子類文件(CustomTableViewCell.swift)中實現如下方法即可

override func setSelected(selected: Bool, animated: Bool) {
? ? super.setSelected(selected, animated: animated)

? ? // Configure the view for the selected state

? ? if selected {
? ? ? ? self.backgroundColor = UIColor.orangeColor()
? ? }else {
? ? ? ? self.backgroundColor = UIColor.whiteColor()
? ? }
}

運行工程,可能你會發現,當你點擊單元格的時候,選中樣式依舊是系統樣式,如下圖:

這是什么原因導致的呢?打開視圖層級,我們就會發現,其實我們已經設置成功了,只是被遮住了,如下圖:

那應該如何解決呢?其實很簡單,只需要修改cell的selectionStyle屬性即可,如下所示:

cell.selectionStyle = UITableViewCellSelectionStyle.None

現在,我們就完成了自定義單元格選中樣式了,特簡單吧?

延伸

有時可能會有這種需求,就是我不需要選中背景色,但是我想在點擊某個單元格的時候閃一下,即背景色突變一下就OK,像這種需求又改如何解決呢?

首先,我們需要實現如下方法,當單元格不管是選中也好,未選中也罷,都設為白色。

override func setSelected(selected: Bool, animated: Bool) {
? ? super.setSelected(selected, animated: animated)

? ? // Configure the view for the selected state

? ? if selected {
? ? ? ? self.backgroundColor = UIColor.whiteColor()
? ? }else {
? ? ? ? self.backgroundColor = UIColor.whiteColor()
? ? }
}

其次,在代理方法中,做如下操作:

func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {

? ? let cell = tableView.cellForRowAtIndexPath(indexPath)

? ? // change the cell background color
? ? cell?.backgroundColor = UIColor.redColor()
}

除了在代理方法中操作,還可以在自定義單元格中實現,效果一致,只是無需通過代理方法實現,具體實現如下:

override func setHighlighted(highlighted: Bool, animated: Bool) {
? ? if highlighted {
? ? ? ? self.backgroundColor = UIColor.redColor()
? ? }else {
? ? ? ? self.backgroundColor = UIColor.whiteColor()
? ? }
}

原文鏈接:https://blog.csdn.net/Hierarch_Lee/article/details/50054637

欄目分類
最近更新