【问题标题】:How to update the CollectionView cell that selected before and now Swift 4?如何更新在 Swift 4 之前和现在选择的 CollectionView 单元格?
【发布时间】:2018-02-26 07:44:53
【问题描述】:

我有一个水平收藏视图。当用户点击一张照片时,会出现一个 UIView 覆盖照片。一次只能选择一张照片。这意味着,如果选择了一张照片,如果我点击另一张照片,上一张照片将恢复正常。

我在下面实现这个代码:

 var previousSelectedIndexPath : IndexPath? 
 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if previousSelectedIndexPath != nil {
            let previousCell = collectionView.cellForItem(at: previousSelectedIndexPath!) as! photoCell
            previousCell.uiViewHeight.constant = 0
        }

        let currentCell = collectionView.cellForItem(at: indexPath) as! photoCell
        currentCell.uiViewHeight.constant = 250
        previousSelectedIndexPath = indexPath
 }

我得到的是,当收藏视图首次启动时,它显示了我想要的行为。但是当我点击一张照片,然后向左滚动,然后再次点击一张新照片,它显示错误

线程 1:致命错误:打开包装时意外发现 nil 可选值

我认为是之前选择的照片不再出现在屏幕上,因此无法更新该照片的 UIView 的约束。

我也尝试实现这个解决方案,但也得到了同样的错误:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let cell = collectionView.cellForItem(at: indexPath) as! photoCell
    cell.uiViewHeight.constant = 250    
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {

    let cell = collectionView.cellForItem(at: indexPath) as! photoCell
    cell.uiViewHeight.constant = 0
}

那么在这种情况下,我该如何解决这个问题呢?

【问题讨论】:

  • cellForItem(at:) 如果单元格不可见,则返回 nil,因此执行 as! 显然会使其崩溃。在cellForRowAtIndexPath中,根据indexPath添加/删除你的效果,在didSelect中,reloadCellForItemAtIndexPath为上一个(如果可见则重新加载,不可见则不做)。
  • @Larme 你能回答一下吗,我可以在我的代码中尝试一下
  • 类似的东西:pastebin.com/q56EEXPJ

标签: ios swift uicollectionview uicollectionviewcell swift4


【解决方案1】:

Ken,不要强制转换您的UICollectionViewCell,您的应用可能会崩溃。

使用这样的安全代码:

if let currentCell = collectionView.cellForItem(at: indexPath) as? photoCell {
      // if succeed, do code
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多