iOS UIScrollView嵌套解决方案

简介:

  界面的复杂化,嵌套滚动视图的方式不可避免(也许是UI设计师的偏爱吧)。
  正常情况下,父子视图多个手势重叠的时候,只会响应最上层的那个手势(也就是子视图的手势),所以有关UIScrollView嵌套时,拖动手势还会首先响应子UIScrollView的手势,而不会响应父UIScrollView的手势;有关手势冲突解决方案见iOS手势冲突解决方案。
  本文记录一下解决的过程和遇到的问题。

解决方案:

1. 利用UIScrollViewisScrollEnabled实现:

这是最先想到方案,实现步骤如下:
1.1 把最上层具体业务的UITableView禁止滚动,那么根据事件响应链,滚动事件事件会由底层的UIScrollView接收并处理;
1.2 到达最大偏移量之后,禁用底层的UIScrollView滚动,同时开启上层的UITableView,使得上层可以滑动。
  思路是可行的,但是现实是残酷的,isScrollEnabled属性为false时,此次滚动手势会被截断,需要再次拖拽才能继续滚动,显然,这样的效果是无法接受的。

2. 父级UIView添加手势,对嵌套的UIScrollView统一管理:

实现步骤如下:
2.1 添加自定义手势,统一处理嵌套UIScrollView的滚动;
2.2 实现UIScrollView滚动和临界值切换的动效。
  由于UIScrollView是有弹性效果的,一般的滑动手势做不到这一点的,所以需要引入UIDynamic模拟力场,实现阻尼效果和回弹效果。想了一下,虽然可以实现,但是为了一个联动滑动,要做这么多的事情,感觉比较繁琐,而且自定义手势做的模拟弹性效果可能和原生UIScrollView的效果还是有一定的差距。有一位同学实现了,见iOS 嵌套UIScrollview的滑动冲突另一种解决方案。

3. 通过手势穿透

  方案1中,除了边界位置会阻断联动滚动外,其他效果还是可以的,那么能不能通过手段解决这个问题呢?答案是肯定的,可以通过手势穿透,即让一个滑动手势既作用于底层的UIScrollView又能作用于上层的业务UITableView,同时控制他们的滚动即可达成目的。

方案3的实现过程:

实现视图结构:
image.png
实现结果:
实现过程:

1.将最外层的垂直方向的设置为自定义继承自UIScrollViewZBYMultiResponseScrollView

class ZBYMultiResponseScrollView: UIScrollView {
    
}

extension ZBYMultiResponseScrollView: UIGestureRecognizerDelegate {
    /// 当一个手势识别器或其他手势识别器的识别被另一个手势识别器阻塞时调用
    /// 返回YES,允许同时识别多个手势。默认实现返回NO(默认情况下不能同时识别两个手势)
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}

2.布局加实现
  如上面实现视图结构的图示,我是用SnapKit布局,所以UIScrollView中添加了内容容器UIView
实现代码:

/// 最外层容器控制器
class ZBYScrollViewListViewController: BaseViewController {
    
    private lazy var viewModel: ZBYScrollViewListViewControllerModel = {
        let viewModel = ZBYScrollViewListViewControllerModel.init()
        viewModel.delegate = self
        return viewModel
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initSubviews()
        self.loadData()
    }
    
    private func initSubviews() {
        self.view.backgroundColor = UIColor.white
        self.navigationBar?.styleOptions = .default
        
        let scrollView = self.viewModel.setScrollView(vc: self)
        scrollView.backgroundColor = .random()
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(kNavigationHeight)
            make.left.right.bottom.equalToSuperview()
            make.width.equalTo(kScreenWidth)
        }
        self.viewModel.setClass()
    }
    
    private func loadData() {
        
    }

}
/// ZBYScrollViewListViewControllerModel最外层容器控制器的Model逻辑层
protocol ZBYScrollViewListViewControllerModelDelegate: NSObjectProtocol {
    func viewModelRefreshChildVCData(_ index: Int) -> Void
}

extension ZBYScrollViewListViewControllerModelDelegate {
    func viewModelRefreshChildVCData(_ index: Int) -> Void {}
}

class ZBYScrollViewListViewControllerModel: NSObject {
    
    public weak var delegate: ZBYScrollViewListViewControllerModelDelegate?
    
    private var titleList = ["流利读", "地道说"]
    
    let headerHeight: CGFloat = 200.0
    let titleHeight: CGFloat = 50
    let maxOffset: CGFloat = 200.0 // 最大偏移量

    /// 是否滑动
    var canScroll = true
    /// 滑动方向:是否向下滑动
    private var isDown: Bool = false
    /// 当前滑动的y值
    private var currentY: CGFloat = 0.0
    /// 子当前滑动的y值
    private var childCurrentY: CGFloat = 0.0

    private weak var currentVC: ZBYTableViewController?
    
    private var isDragging: Bool = false
    
    private weak var vc: UIViewController?
    private weak var titleView: ZBYContainerListTitleView?
    private weak var scrollView: ZBYMultiResponseScrollView?
    private weak var bottomScrollView: UIScrollView?
    private weak var contentView: UIView?
    
    public func setTitleListView() -> ZBYContainerListTitleView {
        let titleView = ZBYContainerListTitleView.init()
        titleView.titleList = self.titleList
        titleView.delegate = self
        self.titleView = titleView
        return titleView
    }
    
    public func setScrollView(vc: UIViewController) -> ZBYMultiResponseScrollView {
        let scrollView = ZBYMultiResponseScrollView.init()
        scrollView.isPagingEnabled = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = true
        scrollView.alwaysBounceHorizontal = false
        scrollView.alwaysBounceVertical = true
        scrollView.delegate = self
        
        let contentView = UIView.init()
        contentView.backgroundColor = .random()
        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.height.equalTo(kScreenHeight - kNavigationHeight + self.headerHeight)
        }
        
        let headerView = UIView.init()
        headerView.backgroundColor = .random()
        contentView.addSubview(headerView)
        headerView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(self.headerHeight)
        }
        
        let titleView = self.setTitleListView()
        titleView.backgroundColor = .random()
        contentView.addSubview(titleView)
        titleView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(self.titleHeight)
        }
        
        let bottomScrollView = UIScrollView.init()
        bottomScrollView.bounces = false
        bottomScrollView.isPagingEnabled = true
        bottomScrollView.alwaysBounceHorizontal = true
        bottomScrollView.alwaysBounceVertical = false
        bottomScrollView.backgroundColor = .random()
        bottomScrollView.delegate = self
        contentView.addSubview(bottomScrollView)
        self.bottomScrollView = bottomScrollView
        bottomScrollView.snp.makeConstraints { (make) in
            make.top.equalTo(titleView.snp.bottom)
            make.height.equalTo(kScreenHeight - kNavigationHeight - self.titleHeight)
            make.left.right.bottom.equalToSuperview()
            make.width.equalTo(kScreenWidth)
        }
        
        let bottomContentView = UIView.init()
        bottomContentView.backgroundColor = .random()
        bottomScrollView.addSubview(bottomContentView)
        self.contentView = bottomContentView
        bottomContentView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.height.equalToSuperview()
        }
        self.vc = vc
        self.scrollView = scrollView
        return scrollView
    }
    
    public func setClass() {
        self.titleView?.titleList = self.titleList
        for item in vc?.children ?? [] {
            item.view.removeFromSuperview()
            item.removeFromParent()
        }
        for (index, item) in self.titleList.enumerated() {
            let questionListVC = ZBYTableViewController.init()
            if index == 0 {
                self.currentVC = questionListVC
            }
            // 传值
//            questionListVC.questionClass = item
            vc?.addChild(questionListVC)
            // 代理和Block幸福二选一
            questionListVC.delegate = self
//            questionListVC.scrollTopBlock = { [weak self] (canScroll) in
//                self?.canScroll = canScroll
//            }
            self.contentView?.addSubview(questionListVC.view)
            questionListVC.view.snp.makeConstraints { (make) in
                make.top.bottom.equalToSuperview()
                make.left.equalTo(CGFloat.init(index) * kScreenWidth)
                make.width.equalTo(kScreenWidth)
                if item == self.titleList.last {
                    make.right.equalToSuperview()
                }
            }
        }
    }

}

extension ZBYScrollViewListViewControllerModel: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 滑动方向
        let translatedPoint = scrollView.panGestureRecognizer.translation(in: scrollView)
        if (translatedPoint.y < 0) {
            self.isDown = false
            NSLog("上滑")
        }
        if (translatedPoint.y > 0) {
            self.isDown = true
            NSLog("下滑")
        }
        if scrollView == self.scrollView {
            if !self.canScroll {
                // 下面代码会造成当一个子VC的TableView滑动到底部是,切换到另一个VC,下滑后;切换回来,再次下滑TableView,出现从maxOffset位置下滑的现象
//                self.currentVC?.canScroll = true
//                scrollView.contentOffset.y = maxOffset
                // 优化后的代码,记录最外层scrollView的滚动位置,从当前滚动位置滑动,而不是从maxOffset位置滑动
                self.currentVC?.canScroll = true
                if self.isDown {
                    if (self.currentVC?.scrollY ?? 0) <= 0 {
                        scrollView.contentOffset.y = maxOffset
                    }
                    else {
                        scrollView.contentOffset.y = self.currentY
                    }
                }
                else {
                    scrollView.contentOffset.y = maxOffset
                    self.currentY = maxOffset
                }
            } else {
                let scrollY = scrollView.contentOffset.y
                // 最外层scrollView的滚动位置
                self.currentY = scrollY
                if scrollY >= maxOffset {
                    scrollView.contentOffset.y = maxOffset
                    self.canScroll = false
                    self.currentVC?.canScroll = true
                }
                else {
//                    scrollView.contentOffset.y = scrollY
                }
            }
        }
        else {
            
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.isDragging = true
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView == self.scrollView {
            
        }
        else {
            self.isDragging = false
            let scrollX = scrollView.contentOffset.x
            let progress = scrollX / kScreenWidth
            self.currentVC = self.vc?.children[Int(progress)] as? ZBYTableViewController
            self.titleView?.selected(index: Int(progress))
    //        // 更新数据
    //        self.delegate?.viewModelRefreshChildVCData(Int(progress))
        }
    }
}

extension ZBYScrollViewListViewControllerModel: ZBYTableViewControllerScrollTopDelegate {
    func childVC(_ vc: ZBYTableViewController, scrollTop isTop: Bool) {
        self.canScroll = isTop
    }
    
    func childVC(_ vc: ZBYTableViewController, scroll contentOffset: CGPoint) {
        self.canScroll = contentOffset.y <= 0
//        self.isDown = contentOffset.y < self.currentY
        self.childCurrentY = contentOffset.y
    }
}

extension ZBYScrollViewListViewControllerModel: ZBYContainerListTitleViewDelegate {
    func selected(_ index: Int) {
        self.bottomScrollView?.setContentOffset(CGPoint.init(x: kScreenWidth * CGFloat.init(index), y: 0), animated: true)
        self.currentVC = self.vc?.children[index] as? ZBYTableViewController
        DispatchQueue.main.asyncAfter(deadline: 0.25) {
            // 更新数据
            self.delegate?.viewModelRefreshChildVCData(index)
        }
    }
}
/// 子控制器中UITableView数据显示
protocol ZBYTableViewControllerScrollTopDelegate: NSObjectProtocol {
    func childVC(_ vc: ZBYTableViewController, scrollTop isTop: Bool) -> Void
    func childVC(_ vc: ZBYTableViewController, scroll contentOffset: CGPoint) -> Void
}

extension ZBYTableViewControllerScrollTopDelegate {
    func childVC(_ vc: ZBYTableViewController, scrollTop isTop: Bool) -> Void {}
    func childVC(_ vc: ZBYTableViewController, scroll contentOffset: CGPoint) -> Void {}
}

class ZBYTableViewController: BaseViewController {
    
    public weak var delegate: ZBYTableViewControllerScrollTopDelegate?
    
    public var canScroll = false
    public var scrollTopBlock: ((Bool) -> Void)?
    public var scrollY: CGFloat {
        get {
            return self.tableView?.contentOffset.y ?? 0
        }
    }
    
    public weak var tableView: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationBar?.isHidden = true
        
        let tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.bounces = true
        tableView.rowHeight = 50
        tableView.backgroundColor = .white
        tableView.separatorStyle = .singleLine
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
        self.tableView = tableView
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        NSLog("123")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NSLog("456")
    }

}

extension ZBYTableViewController: UITableViewDataSource, UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NSLog(scrollView.contentOffset.y)
        if !self.canScroll {    // 无法滚动
            scrollView.contentOffset.y = 0
        }
        else {
            if scrollView.contentOffset.y <= 0 {
                self.canScroll = false
                self.scrollTopBlock?(true)
            }
//            self.delegate?.childVC(self, scrollTop: scrollView.contentOffset.y <= 0)
            self.delegate?.childVC(self, scroll: scrollView.contentOffset)
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "ZBYContainerSubListViewControllerModel"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if cell == nil {
            cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: identifier)
        }
        cell?.selectionStyle = .none
        cell?.textLabel?.text = "标题-\(indexPath.row)"
        return cell!
    }
}
/// 中间标题列表
protocol ZBYContainerListTitleViewDelegate: NSObjectProtocol {
    func selected(_ index: Int) -> Void
}

extension ZBYContainerListTitleViewDelegate {
    func selected(_ index: Int) -> Void {}
}

class ZBYContainerListTitleView: UIView {
    
    public weak var delegate: ZBYContainerListTitleViewDelegate?
    
    public var titleList: [String]? {
        didSet {
            if (titleList?.count ?? 0) <= 0 {
                return
            }
            self.collectionView?.reloadData()
            DispatchQueue.main.async {
                self.collectionView?.selectItem(at: IndexPath.init(row: 0, section: 0), animated: true, scrollPosition: .centeredHorizontally)
                DispatchQueue.main.asyncAfter(deadline: 0.25) {
                    self.delegate?.selected(0)
                }
            }
        }
    }
    
    private var collectionView: UICollectionView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initSubviews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func selected(index: Int) {
        self.collectionView?.selectItem(at: IndexPath.init(row: index, section: 0), animated: true, scrollPosition: .centeredHorizontally)
    }
    
    private func initSubviews() {
        let layout = UICollectionViewFlowLayout.init()
        layout.scrollDirection = .horizontal
        let collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
//        collectionView.bounces = false
        collectionView.register(ZBYContainerListTitleCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: ZBYContainerListTitleCollectionViewCell.description())
        self.addSubview(collectionView)
        self.collectionView = collectionView
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }

}

extension ZBYContainerListTitleView: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.titleList?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = ZBYContainerListTitleCollectionViewCell.cell(collectionView: collectionView, indexPath: indexPath)
        cell.model = self.titleList?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 0, left: 7, bottom: 0, right: 7)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        // 行间距
        return CGFloat.leastNonzeroMagnitude
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        // 列间距
        return 7
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: 116, height: 56)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.delegate?.selected(indexPath.row)
    }
    
}

遇到的问题:

1.临界值问题:
  代码的例子,最外层垂直方向的scrollView滑动到顶部正好是headerView的高度,最外层scrollView显示的内容高度是titleView和内层水平scrollView高度的和。如果有其它特殊要求,请自行计算需要的值。
2.scrollView滑动方向:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 滑动方向
        let translatedPoint = scrollView.panGestureRecognizer.translation(in: scrollView)
        if (translatedPoint.y < 0) {
            self.isDown = false
            NSLog("上滑")
        }
        if (translatedPoint.y > 0) {
            self.isDown = true
            NSLog("下滑")
        }
}

3.最外层垂直方向的scrollView,在切换内部tableView滑动出现回跳现象:
问题代码:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 滑动方向
        let translatedPoint = scrollView.panGestureRecognizer.translation(in: scrollView)
        if (translatedPoint.y < 0) {
            self.isDown = false
            NSLog("上滑")
        }
        if (translatedPoint.y > 0) {
            self.isDown = true
            NSLog("下滑")
        }
        if scrollView == self.scrollView {
            if !self.canScroll {
                // 下面代码会造成当一个子VC的TableView滑动到底部是,切换到另一个VC,下滑后;切换回来,再次下滑TableView,出现从maxOffset位置下滑的现象
                 self.currentVC?.canScroll = true
                  scrollView.contentOffset.y = maxOffset
            } else {
                let scrollY = scrollView.contentOffset.y
                if scrollY >= maxOffset {
                    scrollView.contentOffset.y = maxOffset
                    self.canScroll = false
                    self.currentVC?.canScroll = true
                }
                else {
//                    scrollView.contentOffset.y = scrollY
                }
            }
        }
        else {
            
        }
    }

解决代码:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 滑动方向
        let translatedPoint = scrollView.panGestureRecognizer.translation(in: scrollView)
        if (translatedPoint.y < 0) {
            self.isDown = false
            NSLog("上滑")
        }
        if (translatedPoint.y > 0) {
            self.isDown = true
            NSLog("下滑")
        }
        if scrollView == self.scrollView {
            if !self.canScroll {
                // 优化后的代码,记录最外层scrollView的滚动位置,从当前滚动位置滑动,而不是从maxOffset位置滑动
                self.currentVC?.canScroll = true
                if self.isDown {
                    if (self.currentVC?.scrollY ?? 0) <= 0 {
                        scrollView.contentOffset.y = maxOffset
                    }
                    else {
                        scrollView.contentOffset.y = self.currentY
                    }
                }
                else {
                    scrollView.contentOffset.y = maxOffset
                    self.currentY = maxOffset
                }
            } else {
                let scrollY = scrollView.contentOffset.y
                // 记录最外层scrollView的滚动位置
                self.currentY = scrollY
                if scrollY >= maxOffset {
                    scrollView.contentOffset.y = maxOffset
                    self.canScroll = false
                    self.currentVC?.canScroll = true
                }
                else {
//                    scrollView.contentOffset.y = scrollY
                }
            }
        }
        else {
            
        }
    }

三方轮子:

JXCategoryView

参考链接:

ScrollView嵌套tableView联动滚动最佳实践
嵌套UIScrollview的滑动冲突解决方案

你可能感兴趣的:(iOS UIScrollView嵌套解决方案)