Home > database >  How to Make TableView scroll inside ScrollView behave naturally
How to Make TableView scroll inside ScrollView behave naturally

Time:05-12

I need to do this app. The view hierarchy goes like this

UIScrollView
-UIView (Main View)
--UIView (Top View Container)
--UITableview

When scrolling up the Main View, If table view has many cells, the table view should go to the top, and once it reaches the top. The user should be able to scroll the table view cells. I was able to achieve it but it doesn't scroll naturally.

Screen Idea

Attached my code https://github.com/iamshimak/FinchHomeScreenRedesign.git

CodePudding user response:

First, never put tableview inside a scrollview, it's a bad practice. You could just use tableview header and embed any type of view do you want before the tableview cells.

here's a snipeste on how I deal with it:

//MARK: ConfigureTableView
    private func configureTableView(){
        let footerView = UIView()
        footerView.frame.size.height = 50
        footerView.backgroundColor = .white
        self.tableView.tableFooterView = footerView
        self.tableView.tableHeaderView = self.headerView
        var newFrame = headerView.frame

        newFrame.size.width = view.bounds.width
        newFrame.size.height = 300
        headerView.frame = newFrame
        
        tableView.backgroundView = UIView()
        tableView.backgroundView?.addSubview(backgroundTableView)
    }

as you can see, I embedded a UIView as a footer and another UIView named headerView as a header

but if you insist of using a tableview inside a scrollview, you can try using a scrollview delegate and detech which scrollview is scrolling


func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let yOffset = scrollView.contentOffset.y
    
    if scrollView == self.scrollView {
        if yOffset >= scrollViewContentHeight - screenHeight {
           // logic when using scrollview
        }
    }
    
    if scrollView == self.tableView {
        if yOffset <= 0 {
            // logic when using tableview scrollView
        }
    }

}
  • Related