ios - 在 TableView 中的 Collection View 中同步滚动动画

标签 ios swift uitableview animation uicollectionview

我在许多部分的表格 View 中都有 Collection View (复数)。我们很清楚,一个包含许多部分的 TableView ,每个部分只有一行,该行是一个单独的 Collection View 。

enter image description here

所有设置都运行良好,数据划分良好,代表们都已做好准备,可以识别他们需要识别的所有内容。我的问题有点简单,但同时又很困难:每当我需要以动画方式查找特定单元格时,我都想滚动到特定 Collection View 的位置。

到目前为止,我可以毫无问题地跳转到表部分(indexPath.section)和集合项(indexPath.row)。当我需要与动画一起滚动(同时)时,就会出现问题。

到目前为止我的发现

  1. 我只能通过停用 UITableView 的滚动动画来实现当前目标( UICollectionView 没有它也能表现良好)

  2. 每当我设置 UITableView selectRowscrollToRow 动画标记为 true 然后应用程序崩溃(99% 肯定会发生这种情况,因为我正在尝试访问“不可见”部分因为动画还没有显示)。

相关代码片段

<小时/>
@IBOutlet weak var albumTableView: UITableView!
@IBOutlet weak var stickersCollectionView: UICollectionView!

func locateCell() {
    ...
    let stickerIndex = methodThatReturnsExactIndex()
    let sectionIndex = IndexPath(row: 0, section: stickerIndex.section)
    albumTableView.selectRow(at: sectionIndex, animated: false, scrollPosition: .top)
    let rowIndex = IndexPath(item: stickerIndex.row, section: 0)
    stickersCollectionView.scrollToItem(at: rowIndex, at: 0, animated: true)
}
<小时/>

我在思考 UIScrollViewDelegate 的实验(检测 tableviewcollectionview 何时停止以执行滚动)但这意味着在代码中传播全局变量,并经历艰难的我,这只是等待的竞争条件发生。任何帮助将不胜感激。

最佳答案

首先将您的 tableView 滚动到带/不带动画的特定索引。这将使该单元格可见,现在通过提供该 indexPath 来获取您的单元格,以便您可以访问 tableViewCell 内的 collectionView 对象。然后要求您 collectionView 滚动到特定的 indexPath(带/不带动画)。 使用另一个全局 bool 值来存储 tableView 是否开始滚动。还存储用于集合和 tableView 的 indexPath 并使用 tab

tableViewIsScrolling = true
let yourSelectedIndexPathForTableView = IndexPath(row: 0, section: 4)//store it globally
let yourSelectedIndexPathForCollectionView = IndexPath(row: 10, section: 0)//store it globally

tableView.scrollToRow(at: yourSelectedIndexPathForTableView, at: .middle, animated: false)



func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
    if tableViewIsScrolling {
        tableViewIsScrolling = false
        //Perform your scrolling of CollectionView
        guard let yourCell = tableView.cellForRow(at: yourSelectedIndexPathForTableView) as? YourCell else {return}
        yourCell.collectionView.scrollToItem(at: yourSelectedIndexPathForCollectionView, at: .centeredHorizontally, animated: true)
    }
}

关于ios - 在 TableView 中的 Collection View 中同步滚动动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48754201/

相关文章:

swift - 尝试将 Alamofire 3 请求迁移到带有 header 的版本 4

ios - 设置状态栏颜色以匹配 UISearchBar

ios - 在 iOS 上运行 Scala 代码

ios - RxSwift - 当 UITextField 以编程方式更新时,UILabel 字段未更新

swift - 如何从服务器下载图像并以淡入淡出动画快速显示?

ios - 将数据从一个 TableView 传递到另一个 TableView

iphone - 我想滚动到 TableView 中的一行,选择该单元格然后取消选择它,但在我看到它之前它已被取消选择

ios - iOS 13 及更高版本中未收到来自 Firebase 的推送通知

ios - 使用 @State 变量属性作为绑定(bind)

ios - 如何复制iOS邮件新消息动画