Swift中UITableViewCell中的同步滚动UICollectionViews

Lat*_*nec 0 xcode uitableview ios uicollectionview swift

我有这样的结构:

UITableView-> UITableViewCell-> UICollectionView-> UICollectionViewCell

所以,我想要实现的是,我想让UICollectionViewsUITableViewCells中滚动同步。例如,当您手动滚动第一行的第一个UICollectionView时,我希望其余的UICollectionViews都可以跟随,但是“文本标签” 始终保持在相同位置。(请参见下图)

编辑:我知道我必须以contentOffset某种方式使用,但不知道如何在这种情况下实现。任何帮助,将不胜感激。

点击查看图片

点击查看gif

Dom*_*her 6

好的,我设法做到了这一点,请记住,代码只是出于问题的目的,其中包含许多非通用参数和强制转换,应不惜一切代价避免使用。

MainViewController的类包含tableView:

    protocol TheDelegate: class {
    func didScroll(to position: CGFloat)
}

    class ViewController: UIViewController, TheDelegate {

        func didScroll(to position: CGFloat) {
            for cell in tableView.visibleCells as! [TableViewCell] {
                (cell.collectionView as UIScrollView).contentOffset.x = position
            }
        }

        @IBOutlet var tableView: UITableView!

        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.dataSource = self
        }
    }

    extension ViewController: UITableViewDataSource {
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 100
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as? TableViewCell else { return UITableViewCell() }
            cell.scrollDelegate = self
            return cell
        }
    }
Run Code Online (Sandbox Code Playgroud)

tableViewCell的类:

class TableViewCell: UITableViewCell {

    @IBOutlet var collectionView: UICollectionView!

    weak var scrollDelegate: TheDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        (collectionView as UIScrollView).delegate = self
        collectionView.dataSource = self
    }
}

extension TableViewCell: UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! CollectionViewCell
        cell.imageView.image = #imageLiteral(resourceName: "litecoin.png")
        return cell
    }
}

extension TableViewCell: UIScrollViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrollDelegate?.didScroll(to: scrollView.contentOffset.x)
    }
}
Run Code Online (Sandbox Code Playgroud)

collectionViewCell的类无关紧要,因为它只是实现细节。我将在一秒钟内将此解决方案发布到github。

免责声明:这仅适用于可见单元格。您还需要为准备好重用的单元实现当前滚动状态。我将在github上扩展代码。