gpt4 book ai didi

ios - 在 Swift 的 UITableViewCell 中同步滚动 UICollectionViews

转载 作者:行者123 更新时间:2023-11-28 09:40:51 25 4
gpt4 key购买 nike

我有这样的结构:

UITableView -> UITableViewCell -> UICollectionView -> UICollectionViewCell

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

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

Click to see the image

Click to see the gif

最佳答案

好的,我设法让这个工作正常,请记住代码仅用于问题目的,包含许多非通用参数和强制转换,应不惜一切代价避免。

包含 tableView 的 MainViewController 类:

    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
}
}

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)
}
}

collectionViewCell 的类无关紧要,因为它只是实现细节。稍后我会将此解决方案发布到 github。

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

关于ios - 在 Swift 的 UITableViewCell 中同步滚动 UICollectionViews,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48461698/

25 4 0
文章推荐: ios - 索引超出范围数据 nil swift 3
文章推荐: jquery - 当容器高度改变时动画 scollbars
文章推荐: html - 微软 Word/HTML : Export textbox as
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com