Search code examples
iosswiftuitableviewscrollstatusbar

Scroll to top TableView by tapping status bar not work (with many subviews) SWIFT


I have many views and for each views, many subviews. I tried to specify for each subviews

scrollsToTop = false

but my TableView doesn't scroll to top when I press the status bar. I suppose I missed some views...

SB

I know there is a similar post but it doesn't answer (UITableView scroll to top when tapping status bar at top of the screen)

So I decided to implement this function:

override func viewDidLoad() {   

    super.viewDidLoad()

    checkForScrollViewInView(self.view)

    self.tableView.delegate = self
    self.tableView.dataSource = self
    self.tableView.scrollsToTop = true
}

func checkForScrollViewInView(view:UIView) {
    for subview in view.subviews as [UIView] {

        if subview.isKindOfClass(UITextView) {
            (subview as! UITextView).scrollsToTop = false
        }

        if subview.isKindOfClass(UIScrollView) {
            (subview as! UIScrollView).scrollsToTop = false
        }

        if subview.isKindOfClass(UITableView) {
            (subview as! UITableView).scrollsToTop = false
        }

        if (subview.subviews.count > 0) {
            self.checkForScrollViewInView(subview)
        }
    }
}

But it doesn't work too. I don't know what I miss.


Solution

  • Ok I found why my tableview wouldn't scroll!

    I called my checkForScrollViewInView() function only in the viewDidLoad of my table view's view controller. In order to disable scrollToTop for every child views.

    But I forgot that I had another "active" view controller... In my app I have a left menu which opens to swipe. Calling checkForScrollViewInView() in the left menu's view controller solves my issue.

    func checkForScrollViewInView(view:UIView) {
    
        for subview in view.subviews as [UIView] {
    
            if subview.isKindOfClass(UITextView) {
                (subview as! UITextView).scrollsToTop = false
            }
    
            if subview.isKindOfClass(UIScrollView) {
                (subview as! UIScrollView).scrollsToTop = false
            }
    
            if subview.isKindOfClass(UITableView) {
                (subview as! UITableView).scrollsToTop = false
            }
    
            if (subview.subviews.count > 0) {
                self.checkForScrollViewInView(subview)
            }
        }
    }