前言
在UITableViewCell有一個(gè)屬性selectionStyle,是一個(gè)沒具有屬性,取值如下
typedef NS_ENUM(NSInteger, UITableViewCellSelectionStyle) {
UITableViewCellSelectionStyleNone,
UITableViewCellSelectionStyleBlue,
UITableViewCellSelectionStyleGray,
UITableViewCellSelectionStyleDefault NS_ENUM_AVAILABLE_IOS(7_0)
};
在xib是這樣選擇的 
其要實(shí)現(xiàn)的效果是就是在cell點(diǎn)擊的時(shí)候,顯示一個(gè)選中效果,并且提供了幾種可選值

需求
但是在 UICollectionViewCell 并未提供這樣的屬性,一番百度之后發(fā)現(xiàn)在UICollectionView提供了一下代理方法

代理方法
// 相當(dāng)于開關(guān),允許其高亮,實(shí)現(xiàn)的時(shí)候返回`true`
func collectionView(_ collectionView: UICollectionView,
shouldHighlightItemAt indexPath: IndexPath) -> Bool
// 是高亮?xí)r需要做的操作
func collectionView(_ collectionView: UICollectionView,
didHighlightItemAt indexPath: IndexPath)
// 取消高亮的時(shí)候操作
func collectionView(_ collectionView: UICollectionView,
didUnhighlightItemAt indexPath: IndexPath)
目前的需求是是在高亮的時(shí)候,通過UICollectionView的
func cellForItem(at indexPath: IndexPath) -> UICollectionViewCell?
方法獲取到cell,然后改變其背景色為灰色,然后在取消高亮的時(shí)候恢復(fù)其原來的顏色白色
問題
在實(shí)現(xiàn)的過程中,發(fā)現(xiàn)沒有起作用,經(jīng)過斷點(diǎn)調(diào)試,以及各種可能性的推斷以及調(diào)試發(fā)現(xiàn) 可能性的原因是點(diǎn)擊高亮和取消高亮的方法系統(tǒng)是接連調(diào)用,只看到最后的取消高亮的白色,所以給人一種并未起作用的錯(cuò)覺,不過這只是一種推斷
解決
所以我想在取消高亮的方法進(jìn)行一定的延時(shí),使其高亮的顏色得以展示,然后在實(shí)現(xiàn)區(qū)取消高亮,目前是可以實(shí)現(xiàn)了,代碼如下
//MARK: cell點(diǎn)擊選中
func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.cellSelectedBgColor
}
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
delay(0.25) {
cell?.backgroundColor = UIColor.white
}
}
后續(xù)
- 在網(wǎng)上查詢這問題時(shí),答案并不是很多,而且?guī)缀鯖]有起作用的,延時(shí)的方法是自己想出來的,如果有問題后續(xù)會(huì)更新博客
- 還有就是網(wǎng)上有說這種設(shè)置會(huì)有類似復(fù)用問題,但是經(jīng)過我測(cè)試,以及我目前的項(xiàng)目場(chǎng)景,即點(diǎn)擊cell以后會(huì)跳轉(zhuǎn)一個(gè)新的cell,并且點(diǎn)擊完之后要恢復(fù)其本來的顏色,所以并未發(fā)現(xiàn)復(fù)用問題
- 歡迎各位拍磚溝通