LoginSignup
10
11

More than 3 years have passed since last update.

[Swift 5]TabBarのボタン(TabBarItem)をタップで画面をModal表示する簡単な方法

Posted at

TabBarControllerで実装したボトムタブを選択すると、通常は画面が切り替わります。
今回は、特殊なボタンとして画面をModal(下から上へ出現)表示させたい時の実装です。

(真ん中のボタンが丸く縁取られているアプリに多いと思います)

Modalで開きたい画面クラスがTargetViewControllerと仮定して解説していきます。

ソースコード

TabBarController.swift
import UIKit

final class TabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        delegate = self // UITabBarControllerDelegate
    }
}

// MARK: - UITabBarControllerDelegateに適合
extension TabBarController: UITabBarControllerDelegate {
    // TabBarItemが選択された時に呼ばれる
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        // TabBarItemタップでModal表示をする画面を指定して実装
        if viewController is TargetViewController {
            if let newVC = UIStoryboard(name: "Target", bundle: nil).instantiateInitialViewController() {
                tabBarController.present(newVC, animated: true, completion: nil)
                return false
            }
        }
        return true
    }
}

実装手順

  1. delegate = selfを書くのを忘れない
  2. extentionUITabBarControllerDelegateに適合する
  3. tabBarController(_:shouldSelect:)->Boolメソッドを実装
  4. 開かれるViewControllerが対象のものだったら、という条件でif分岐
  5. あとは、ViewControllerをインスタンス化し、present(_:animated:completion)メソッドで画面をModal表示させればOKです!

NavigationControllerを使用している場合

TargetViewControllerでNavigationItemを使いたい等の理由でNavigationControllerを使用する場合

TabBarController.swift
if viewController.children.first is TargetViewController {

というようにすればNavigationControllerが間にあっても判定可能です。

もし、もっと簡単な方法があればぜひ教えてください。

10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11