Dennis van Mazijk
Dennis van Mazijk

Reputation: 205

Swift - Selected tab bar index not triggering scroll to top

I have a tab bar with five items, and I am trying to add a functionality to scroll to the top when the user taps the tab bar item again. Added the UITabBarControllerDelegate to the views where I want to trigger the event and also created a function to determine the selected tab bar index.

When I open the app, index 0 is auto-selected and works perfectly. The view auto scrolls to the top when I scroll down and tap the tab bar index. The problem occurs when I go to index 1 and trigger the scroll there. It somehow completely removes the auto-scroll from my first tab bar item.

Selecting other tab bar items without the auto scroll does not affect index 0 at all.

Home (index 0)

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    let tabBarIndex = tabBarController.selectedIndex
    if tabBarIndex == 0 {
        self.collectionView?.setContentOffset(CGPoint(x: 0, y: -10), animated: true)
    }
}

Users (index 1)

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    let tabBarIndex = tabBarController.selectedIndex
    if tabBarIndex == 1 {
        self.tableView?.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
    }
}

Upvotes: 0

Views: 11194

Answers (1)

rmaddy
rmaddy

Reputation: 318804

Anything with a delegate property can only have one delegate assigned to it at any given time. What ever set the delegate most recently will receive the next delegate method call.

In your case you can probably reset the tab controller's delegate to self in each view controller's viewDidAppear method since you want the currently visible view controller to be the current tab controller delegate.

Add the following to each view controller that needs to be the tab controller's delegate:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.tabBarController?.delegate = self
}

Upvotes: 5

Related Questions