31
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

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

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/

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
31
Help us understand the problem. What are the problem?