我在许多部分的表格 View 中都有 Collection View (复数)。我们很清楚,一个包含许多部分的 TableView ,每个部分只有一行,该行是一个单独的 Collection View 。
所有设置都运行良好,数据划分良好,代表们都已做好准备,可以识别他们需要识别的所有内容。我的问题有点简单,但同时又很困难:每当我需要以动画方式查找特定单元格时,我都想滚动到特定 Collection View 的位置。
到目前为止,我可以毫无问题地跳转到表部分(indexPath.section)和集合项(indexPath.row)。当我需要与动画一起滚动(同时)时,就会出现问题。
到目前为止我的发现
我只能通过停用
UITableView
的滚动动画来实现当前目标(UICollectionView
没有它也能表现良好)每当我设置
UITableView
selectRow 或 scrollToRow 动画标记为 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
的实验(检测 tableview 和 collectionview 何时停止以执行滚动)但这意味着在代码中传播全局变量,并经历艰难的我,这只是等待的竞争条件发生。任何帮助将不胜感激。
最佳答案
首先将您的 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/