我有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等...
答案 0 :(得分:1)
UICollectionView
重复使用UITableView
之类的单元格。当一个单元格在屏幕外滚动时,它将被添加到队列中,并将被重新用于下一个要在屏幕上滚动的单元格(例如单元格4,7 ...)。
只需删除translucentView
即可解决此问题:
UIView.animateWithDuration(0.4, animations: { () -> Void in
translucentView.alpha = 1.0
}) { (finish) -> Void in
translucentView.removeFromSuperview()
}
您可以在translucentView
中创建ItemCell
并使用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
})
}
答案 1 :(得分:0)
您是否正确设置了numberOfSectionsInTableView
?
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}