简体   繁体   中英

How do I detect when the number of tabs changes on orientation in UITabBarController?

On an iPhone 13 pro max, 5 tabs are showing in portrait and 8 tabs are showing in landscape.

I want to detect when there is a change in the number of tabs (ex: 8 to 5 or 5 to 8).

Sometimes the new tabs are getting rendered after deviceOrientationDidChange where tabBar.items?.count still points to the old value.

One solution is to override viewDidLayoutSubviews .

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    print("didLayout:", self.tabBar.items!.count)
}

That code assumes self is a class that extends UITabBarController .

One issue with this solution is that viewDidLayoutSubviews is likely to be called more than once (probably two times) when the device is rotated so you have to adjust your logic to handle this.


Another possible solution is to override viewWillTransition :

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    coordinator.animate(alongsideTransition: nil) { context in
        print("didTransition:", self.tabBar.items!.count)
    }
}

The trailing closure is a completion block that is called after the rotation animation completes.

One issue with this solution is that it is not called initially. It is only called after the device is rotated or if the split view mode is changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM