【问题标题】:Collection view cell scrollToItem cast fails [Swift]集合视图单元格 scrollToItem 转换失败 [Swift]
【发布时间】:2020-05-04 16:04:11
【问题描述】:

在我的 swift 应用程序中,我有一个包含很多项目的集合视图,我想滚动到一个项目,然后设置 collectionview 单元格自定义类的适当性,但转换失败,为什么? 这是我的代码,我省略了一些明显的步骤,但结果是打印“Cast failed”:

类视图控制器:UIViewController {

lazy var collectionView: UICollectionView = {
    let cv = UICollectionView(frame: self.view.bounds, collectionViewLayout: UICollectionViewFlowLayout())
    cv.backgroundColor = .gray
    cv.register(Cell.self, forCellWithReuseIdentifier: Cell.id)
    cv.delegate = self
    cv.dataSource = self
    return cv
}()

}

扩展 ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.id, for: indexPath) as! Cell
    cell.backgroundColor = .purple
    cell.label.text = "\(indexPath)"
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if indexPath.item == 14 {
        collectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: .top, animated: true)
        guard let cell = collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? Cell else {
            print("Cast fails")
            return
        }
        cell.label.text = "Something"
    }
}

}

这是我找到的解决方案:

extension UICollectionView {
    func scrollToItem(at indexPath: IndexPath, at position: UICollectionView.ScrollPosition, completion: @escaping () -> ()) {
        scrollToItem(at: indexPath, at: .top, animated: true)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            completion()
        }
    }
}

【问题讨论】:

    标签: swift uicollectionview uicollectionviewcell uicollectionviewlayout


    【解决方案1】:

    转换失败,因为在您查询它时(该特定索引的)单元格不可见

    guard let cell = collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? Cell else {
      print("Cast fails")
      return
    } 
    

    您可以尝试设置 , at: .top, animated: false) 或将上述代码 sn-p 包装在 Dispatch after block 中

    顺便说一句,您最好更改 dataSource 数组并重新加载该索引,这样您就不需要等待

    // change source array at that index
    // scroll to that row with/without animation
    // make sure you set value for the cell label in cellForRowAt table's datasource method 
    

    【讨论】:

    • 好的,为什么我不能使用 performBatchUpdates 来获取完成,而不是使用异步线程?
    • 这是另一种选择,试试吧
    • 我无法更改源代理,因为我正在创建一个类似于 whatsapp 的聊天,当您单击回复时,集合视图会滚动到原始消息然后突出显示它。
    • 好的,我已经发布了解决方案,谢谢 Sn_Khan,0.5 对我来说是正确的时间
    猜你喜欢
    • 2023-03-19
    • 2020-04-16
    • 2016-05-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 2017-11-25
    相关资源
    最近更新 更多