我正在使用带有XCode 7测试版的Swift 2。我正在使用包含图像和标签的单元格呈现UICollectionView。在viewLoad时应隐藏图像。
这是我的代码:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ContactCell", forIndexPath: indexPath) as! ContactCell
cell.contactName.text = contactsNames[indexPath.row]
cell.selectedIcon.hidden = true
return cell
}
// selection of the item
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ContactCell", forIndexPath: indexPath) as! ContactCell
cell.selectedIcon.hidden = false
}
我还在加载过程中尝试放入第一个collectionView方法cell.selectedIcon.hidden = true
,它显示了项目。但交互仍然不起作用(当我点击项目时,它没有显示)。
你能建议如何解决这个问题吗?谢谢
首先阅读关于dequeueReusableCellWithReuseIdentifier
方法的内容:
当要求为集合视图提供新单元格时,从数据源对象调用此方法。如果现有单元格可用,此方法会将其排成队列,或者根据您之前注册的类或nib文件创建一个新单元格。
要访问一个特定的单元格,您可以使用几个选项,但在您的特定情况下,我认为方法cellForItemAtIndexPath(_:)
(这种方法与您设置单元格初始值的方法不同,如上所述)是最佳选择,如下所示:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ContactCell
cell.selectedIcon.hidden = false
}
我希望这对你有帮助。
尝试在项目函数的选择中重新加载数据。
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ContactCell", forIndexPath: indexPath) as! ContactCell
cell.selectedIcon.hidden = false
collectionView.reloadData()
}
我有同样的功能,但对于tvOS,我认为它也适用于iOS。试试看,也许行得通。
这是代码:
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
if let prev = context.previouslyFocusedView as? ContactCell {
UIView.animateWithDuration(0.1, animations: { () -> Void in
prev.selectedIcon.hidden = true
})
}
if let next = context.nextFocusedView as? ContactCell{
UIView.animateWithDuration(0.1, animations: { () -> Void in
next.selectedIcon.hidden = false
})
}
}