網站首頁 編程語言 正文
本文實例為大家分享了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
相關推薦
- 2023-07-05 React通過useContext特性實現組件數據傳遞
- 2023-01-17 python實現鄰接表轉鄰接矩陣_python
- 2023-01-07 Python個人博客程序開發實例用戶驗證功能_python
- 2022-08-05 react+react-beautiful-dnd實現代辦事項思路詳解_React
- 2022-08-17 React大屏可視化腳手架教程示例_React
- 2022-07-22 springboot項目整合配置knife4j
- 2022-05-02 Redis可視化連接服務器的方法_Redis
- 2023-07-07 Spring整合Junit單元測試
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支