えむじぃのアプリ開発

えむじぃのアプリ開発

元大手IT企業SE、現ベンチャー企業CTOのブログです。

【Swift】UITabBarを使って画面遷移する方法

今回はUITabBarを使って画面遷移する方法をこの記事で説明します。

この記事のポイント・UITabBarDelegateを使用

UITabBarを使って画面遷移する方法

TabBarの設定

Main.storryboardのViewControllerにTabBarを配置します。

f:id:masGo:20201021082629p:plain

ViewControllerの設定

UITabBarDelegateを追加します。

class ViewController: UIViewController, UITabBarDelegate  {
    @IBOutlet weak var tabMenuBar: UITabBar!

 

override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tabMenuBar.delegate = self

 

TabBarActionを追加します。

func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        switch item.tag{
        case 1:
            print("1") // カレンダーアイコンをタップした場合
            let storyboard: UIStoryboard = self.storyboard!
            let nextView = storyboard.instantiateViewController(withIdentifier: "Main")
            nextView.modalPresentationStyle = .fullScreen
            present(nextView, animated: true, completion: nil)

        case 2:
            print("2") // 設定アイコンをタップした場合
            let storyboard: UIStoryboard = self.storyboard!
            let nextView = storyboard.instantiateViewController(withIdentifier: "Config")
            nextView.modalPresentationStyle = .fullScreen
            present(nextView, animated: true, completion: nil)
            
        default : return
            
        }
    
    }

 

f:id:masGo:20201021085113p:plain

 

let nextView = storyboard.instantiateViewController(withIdentifier: "Main")
// 上記の『withIdentifier: "Main"』は遷移先画面のStoryboardに設定した値をセットします。

 

これでUITabBarを使って画面遷移するようになります。