首页 > 解决方案 > 在水平 CollectionView 内使用 TableView 垂直滚动

问题描述

我有一个水平UICollectionView(带分页),其中每个单元格都有一个 fullscreen UITableView。父 ViewController 有一个带有大标题的导航栏,在垂直滚动期间会出现动画。但是,由于我的表格视图位于水平集合视图中,因此大导航栏在滚动时不会动画。

我尝试了一种解决方案,即为 tableview 滚动设置委托,然后设置集合视图的 y 偏移量,但结果出现故障并且无法正常工作。

这是我当前的代码(没有 TableView/CollectionView 委托/数据源方法)

class HomeViewController: UIViewController, HomeCellDelegate {

    var delegate: HomeViewControllerDelegate!
    var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        create()
    }

    func create() {
        view.backgroundColor = .background
    
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = .zero
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.addSubview(collectionView)
        collectionView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(HomeCell.self, forCellWithReuseIdentifier: "cellID")
    }

    //Delegate from UICollectionView cell (the table view)
    func tableViewDidScroll(_ contentOffset: CGPoint) {
        collectionView.contentOffset.y = contentOffset.y //Glitches
    }
}



protocol HomeCellDelegate {
     func tableViewDidScroll(_ contentOffset: CGPoint)
}
class HomeCell: UICollectionViewCell {

    var events = [String]()

    let tableView = UITableView()
    var delegate: HomeCellDelegate!

    override init(frame: CGRect) {
        super.init(frame: frame)
        create()
    }

    func create() {
        backgroundColor = .clear
    
        addSubview(tableView)
        tableView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
        tableView.contentInsetAdjustmentBehavior = .never
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = CGPoint(x: 0.0, y: scrollView.contentOffset.y + scrollView.adjustedContentInset.top)
        delegate.tableViewDidScroll(offset)
    }

    required init?(coder: NSCoder) {
        fatalError()
    }
}

标签: iosswiftuitableview

解决方案


推荐阅读