[Swift5] UIButton Tap to switch tabs (applicable)

What I want to do this time

In the Controller displayed by the modal transition that is often seen on the login page etc. When you tap the UIButton, the specified Tab is selected and the modal screen is closed.

In other words, you can switch tabs on the back side of the modal screen.

Behavior video https://gyazo.com/828856720584516e602ebffd83f71c22

Taking the attached video as an example, tap tab 1 (account tab) to display the modal screen, When you tap the cancel button, it switches to the tab (news tab) and then closes the modal screen.

This can be applied even if the number of tabs increases, and it can be applied not only to UIButton but also to various situations.

Implementation code

//Called when you tap the cancel button
@objc func cancelTap() {
        
  //① Get an instance of the tab bar
  if let tabBarController = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController {
            
    //② Select the news tab (0 is the leftmost)
    DispatchQueue.main.async {
      tabBarController.selectedIndex = 0
    }
    //③ Close the modal screen
    dismiss(animated: true, completion: nil) 
}

Actually, I was searching to implement it, but I had a little trouble with Swif5 support and recent articles. Please refer to it!

Recommended Posts

[Swift5] UIButton Tap to switch tabs (applicable)
Swipe to switch screens