设置:
我在 Storyboard 上创建了一个 UICollectionView,委托(delegate)连接到 Controller ,面向水平滚动。每个 UICollectionViewCell 内部都有一个 UITableView,委托(delegate)给同一个 Controller 。 Collection View 被分页。一次大约有 3.5 个细胞可见。
问题:
如果我在 Collection View 上水平滚动,以便现在“分页”超过 1 个长度,然后尝试垂直滚动包含的 UITableView,则 UICollectionView 内容偏移会通过动画设置为 0,0 的内容偏移来重置。保持触摸事件,并且出队的单元格继续其滚动 Action 。我不希望在用户滚动 tableview 时重置 collection view
注意事项:
使用 iPad 模拟器
这是一张示例图片。每列都是一个包含 UITableView 的 UICollectionViewCell。列中的每一行都是一个 UITableViewCell。如果我不在 UICollectionView 的内容偏移量 0,0 处,并且我在任何 TableView 上滚动, Collection View 将动画回到内容偏移量 0,0
最佳答案
有点过时的答案,但可能会对某人有所帮助。 首先在 collectionView 中设置 scrollView delegate 返回主视图 Controller 。
在 View Controller 中声明:
private var scrollViewOffset: CGPoint = CGPointZero
在主视图 Controller 中添加以下代码:
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView == self.tableView {
return
}
self.scrollViewOffset = scrollView.contentOffset
for cell in self.tableView.visibleCells {
(cell as! MyCell).collectionView.contentOffset = scrollView.contentOffset
}
}
完成这一部分后,下一部分就是您所缺少的:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MyCell = tableView.dequeueReusableCellWithIdentifier("CellID", forIndexPath: indexPath) as! MyCell
cell.delegate = self
cell.collectionView.reloadData()
cell.collectionView.layoutIfNeeded() // THIS PART IS NEEDED IN ORDER NOT TO SCROLL TO 0, 0 OFFSET
return cell
}
并在:
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let cell: MyCell = cell as! MyCell
cell.collectionView.contentOffset = self.scrollViewOffset
}
MyCell 的内容应该是这样的:
protocol MyCellDelegate {
func scrollViewDidScroll(scrollView: UIScrollView)
}
class MyCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var delegate: MyCellDelegate? = nil
// Do collection view display logic here
// ...
// After that implement scrollview delegate
func scrollViewDidScroll(scrollView: UIScrollView) {
if (self.delegate != nil) {
self.delegate?.scrollViewDidScroll(scrollView)
} else {
print("Missing delegate init")
}
}
}
此答案适用于 Xcode 7.3
关于ios - UICollectionView 在滚动嵌套的 UITableView 后重置内容偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32192712/