LoginSignup
44
31

More than 5 years have passed since last update.

UITabBarControllerをコードから使ってみる

Posted at

UITabBarController

タブを押すとページを切り替えられるUIです。

プロジェクト作成時にtabbed Applicationを選択してもよいのですが、途中で仕様変更があった時などには対処できません。

以下、SingleViewApplicationから作った場合でも実装できる、tabBarControllerを利用したコードです。

Simulator Screen Shot 2015.11.03 1.02.37.png

確認環境

Xcode 7.1(swift2)
iOS 9.1(Simulator)

コード

git -> https://github.com/ha1fha1f/tabViewSample

MainTabController.swift
import UIKit

class MainTabController: UITabBarController {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        var viewControllers: [UIViewController] = []

        let firstViewController = FirstViewController()
        firstViewController.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.MostRecent, tag: 1)
        viewControllers.append(firstViewController)

        let secondViewController = SecondViewController()
        secondViewController.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.MostViewed, tag: 2)
        viewControllers.append(secondViewController)

        let thirdViewController = ThirdViewController()
        thirdViewController.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Contacts, tag: 3)
        viewControllers.append(thirdViewController)

        self.setViewControllers(viewControllers, animated: false)


        // なぜか0だけだと選択されないので1にしてから0に
        self.selectedIndex = 1
        self.selectedIndex = 0
    }
}

ここでインスタンスを生成しているFirstViewController、SecondViewController、ThirdViewControllerは任意です。
利用したいViewControllerのインスタンスを設定してください。

タブの数なども自動的に変更してくれるので、

  1. 必要なインスタンスをすべて生成
  2. 各インスタンスのtabBarItemを設定
  3. viewControllerのインスタンスのArrayを作る
  4. self.setViewControllersに渡す

だけでokです。

UIViewControllerを継承するときのように書けばよいです。だいたいおなじメソッドを持っているので。

storyboardでinitialViewControllerをMainTabControllerにすれば操作は完了です。

仕組み

自動的に、UITabBarControllerの上のレイヤーにcontentView、更にその上のレイヤーにtabBarをのせてくれています。

tabBarItem

システムで定義されているものを使っています。画像を用いることもできます。

初期選択

self.selectedIndex
に値をセットすると、そのアイテムをコードから選択させることができます。

ここでは1をセットするとそのままセットされるのですが、0だけだとbarItemが青くならないので、一度1にしてから0にしています(原因わかる方いれば教えて下さい)

44
31
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
44
31