有点过时的答案,但可能会帮助某人。
首先在collectionView中设置scrollView委托返回主视图控制器。
在视图控制器中声明:
private var scrollViewOffset: CGPoint = CGPointZero
在主视图控制器中添加以下代码:
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