LoginSignup
31

More than 5 years have passed since last update.

swiftでUITabBarの特定のタブをタップした時にモーダル

Last updated at Posted at 2015-02-25

shouldSelectViewControllerで押せれたタブに紐付くViewControllerが特定のViewControllerであった場合に、タブの切り替えを行わずにモーダルを出す。

StoryBoardを使っている前提です。
SampleTabBarControllerをStoryBoard上のTabBarControllerに紐付けます。

SampleTabBarController.swift
class SampleTabBarController: UITabBarController, UITabBarControllerDelegate {

    func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {

        if viewController is DummyViewController {
            // DummyViewControllerはモーダルを出したい特定のタブに紐付けたViewController
            if let currentVC = self.selectedViewController{
                //表示させるモーダル
                let modalViewController: UIViewController = UIViewController()
                //わかりやすく背景を赤色に
                modalViewController.view.backgroundColor = UIColor.redColor()
                currentVC.presentViewController(modalViewController, animated: true, completion: nil)
            }
            return false
        }
        return true
    }

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

モーダルを出したいタブに紐付けられたViewController(DummyViewController)はダミー。
もっとスマートな方法は無いのかしら?

参考URL
http://blog.ryotarai.info/blog/2011/08/17/uitabbar-modal-view/

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
31