How to Make the scroll of a TableView inside ScrollView behave naturally

后端 未结 13 2037
无人及你
无人及你 2020-12-07 08:22

I need to do this app that has a weird configuration.

As shown in the next image, the main view is a UIScrollView. Then inside it should have a UIPageView, and each

相关标签:
13条回答
  • 2020-12-07 08:59

    The solution to simultaneously handling the scroll view and the table view revolves around the UIScrollViewDelegate. Therefore, have your view controller conform to that protocol:

    class ViewController: UIViewController, UIScrollViewDelegate {
    

    I’ll represent the scroll view and table view as outlets:

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var tableView: UITableView!
    

    We’ll also need to track the height of the scroll view content as well as the screen height. You’ll see why later.

    let screenHeight = UIScreen.mainScreen().bounds.height
    let scrollViewContentHeight = 1200 as CGFloat
    

    A little configuration is needed in viewDidLoad::

    override func viewDidLoad() {
        super.viewDidLoad()
    
        scrollView.contentSize = CGSizeMake(scrollViewContentWidth, scrollViewContentHeight)
        scrollView.delegate = self
        tableView.delegate = self 
        scrollView.bounces = false
        tableView.bounces = false
        tableView.scrollEnabled = false
    }
    

    where I’ve turned off bouncing to keep things simple. The key settings are the delegates for the scroll view and the table view and having the table view scrolling being turned off at first.

    These are necessary so that the scrollViewDidScroll: delegate method can handle reaching the bottom of the scroll view and reaching the top of the table view. Here is that method:

    func scrollViewDidScroll(scrollView: UIScrollView) {
        let yOffset = scrollView.contentOffset.y
    
        if scrollView == self.scrollView {
            if yOffset >= scrollViewContentHeight - screenHeight {
                scrollView.scrollEnabled = false
                tableView.scrollEnabled = true
            }
        }
    
        if scrollView == self.tableView {
            if yOffset <= 0 {
                self.scrollView.scrollEnabled = true
                self.tableView.scrollEnabled = false
            }
        }
    }
    

    What the delegate method is doing is detecting when the scroll view has reached its bottom. When that has happened the table view can be scrolled. It is also detecting when the table view reaches the top where the scroll view is re-enabled.

    I created a GIF to demonstrate the results:

    0 讨论(0)
提交回复
热议问题