您不需要集合視圖單元格內的按鈕,只需在按下時設置其高亮顏色即可。只需將單元格的selectedBackgroundView
設置爲與您的單元具有相同寬度和高度的視圖,然後爲該視圖指定backgroundColor
,以便突出顯示該單元格。
A(髒)實現我所做的是這樣的:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as UICollectionViewCell
cell.selectedBackgroundView = {
let bgview = UIView(frame: CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height))
bgview.backgroundColor = UIColor.redColor()
return bgview
}()
return cell
}
然後,只需取消選擇didSelectItemAtIndexPath
細胞。 「壓下」將自動處理,取消動畫僅在用戶擡起手指時觸發。
我認爲這很髒,因爲您每次設置selectedBackgroundView
時,該單元在cellForItemAtIndexPath:
中被重新使用以供重用。我會做的是創造一個UICollectionViewCell
子類,在那裏設置它的selectedBackgroundView
,並在集合視圖使用registerNib:
或registerClass:
註冊該單元格。
地址:清潔版。在您的自定義集合視圖細胞亞類,分配backgroundView
和selectedBackgroundView
:
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundView = {
let view = UIView()
view.backgroundColor = UIColor.yellowColor()
return view
}()
self.selectedBackgroundView = {
let view = UIView()
view.backgroundColor = UIColor.redColor()
return view
}()
}
而且在你看來controlle的相關方法,集合視圖的數據源,並委託:
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.registerClass(NSClassFromString("test.CustomCollectionViewCell"), forCellWithReuseIdentifier: "CELL")
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as UICollectionViewCell
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
}
與使用UILabel代替UIButton的普通UICollectionViewCell有什麼不同,那麼只需更改單元格的contentView的backgroundColor?您的按鈕似乎沒有做任何特別的事情,並且注意到集合或表視圖單元格內的按鈕會延遲其向下觸摸動畫/高光,因爲單元格本身會首先檢查選擇事件。 –
@Matt事實上,按鈕並不特別,它存在的唯一原因是因爲'UICollectionViewCell'不是'UIControl',因此您無法檢測到TouchDown,TouchDragEnter,TouchCancel等,因此無法在出現時更改外觀感動。你可以當它被輕敲('didSelectItemAtIndexPath'),但沒有觸及。 – Joey