![](/img/trans.png)
[英]UICollectionView not calling didSelectItemAtIndexPath
[英]didSelectItemAtIndexPath modifying multiple cells in UICollectionView
我有30個項目的收藏視圖,並希望在印刷時執行某些操作。 我這樣做:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ItemCell
var translucentView = ILTranslucentView(frame: CGRectMake(0, 0, cell.contentView.frame.size.width, cell.contentView.frame.size.height))
translucentView.translucentAlpha = 0.9
translucentView.translucentStyle = UIBarStyle.BlackTranslucent
translucentView.translucentTintColor = UIColor.clearColor()
translucentView.backgroundColor = UIColor.clearColor()
translucentView.alpha = 0.0
cell.contentView.addSubview(translucentView)
UIView.animateWithDuration(0.4, animations: {
translucentView.alpha = 1.0
})
}
該功能將按預期工作,但是視圖不僅會出現在所單擊的單元格上,還會出現在屏幕上不可見的相同位置的單元格上。 因此,如果屏幕上有3個可見的單元格,而我點擊數字1,那么當我滾動查看時,該視圖已添加到單元格4、7等。
UICollectionView
重用像UITableView
這樣的單元格。 當一個單元在屏幕外滾動時,它被添加到隊列中,並將被重新用於下一個要在屏幕上滾動的單元(例如,單元4、7 ...)。
只需刪除translucentView
解決此問題:
UIView.animateWithDuration(0.4, animations: { () -> Void in
translucentView.alpha = 1.0
}) { (finish) -> Void in
translucentView.removeFromSuperview()
}
您可以在ItemCell
創建translucentView
並在cellForItemAtIndexPath
方法中更新其狀態:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellIdentifier, forIndexPath: indexPath) as! ItemCell
if find(collectionView.indexPathsForSelectedItems() as! [NSIndexPath], indexPath) != nil {
cell.translucentView.alpha = 1.0
} else {
cell.translucentView.alpha = 0.0
}
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ItemCell
UIView.animateWithDuration(0.4, animations: {
cell.translucentView.alpha = 1.0
})
}
override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ItemCell
UIView.animateWithDuration(0.4, animations: {
cell.translucentView.alpha = 0.0
})
}
像這樣正確設置了numberOfSectionsInTableView
嗎?
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.