LoginSignup
72
74

More than 5 years have passed since last update.

UITabBarController基礎【Swift3.0】

Posted at

この記事で理解できること

  • タブの追加方法
  • タブアイコンの指定方法
  • タブアイコンのカスタマイズ方法
  • タブバーのカスタマイズ方法

1. プロジェクトの用意

前準備として「TabbedApplication」をテンプレートに指定してプロジェクトを作成します。ストーリーボードは図のようになっているはずです。
0.png

2. タブの追加

タブを追加してみます。新しいタブに対応するViewControllerを一つ増やします。TabBarControllerから追加したViewControllerへ向けてControl + ドラッグします。ポップアップからview controllersを選択します。
1.png
タブの並びを変更したい時は、TabBarController上のアイコンをshiftを押しながらドラッグします。

3. タブアイコンの指定

タブアイコンの指定はTabBarControllerではなく、ViewControllerの下部を選択状態にしてから指定します。ここではシステムアイコンのFavoritesを指定しています。
2.png

4. カスタムタブアイコンの指定

デフォルトのものからカスタムアイコンに変更してみます。前準備としてImage Setを作成しておきましょう。私の場合は、1xには25px,2xには50px,3xには75pxのサイズを割り当てることが多いです。今回はmyFirstという名前のImage Set作成しました。

3.png

System ItemCustomに、selected imagemyFirstに変更します。Bar Itemのほうも忘れずにImagemyFirstを指定します。未選択時のアイコンの状態の設定となります。
4.png

5. 確認してみる

ここで一度ビルドしてみます。
4-2.png

6. タブバーをカスタマイズする

TabbarControllerのカスタムクラスを用意します。メニュー:File → New → FileでCocoa Touch Classをテンプレとして選び、SubclassにUITabBarControllerを指定します。クラス名はMyTabBarControllerとしました。
5.png
ストーリーボード上のMyTabBarControllerを選択し、Custom Class欄で、MyTabBarControllerを指定します。
6.png

例としてタブバーのアイコンと背景を変更してみましょう。MyTabBarController.swiftに変更のコードを追加します。

MyTabBarController.swift


//
//  MyTabBarController.swift
//

import UIKit

class MyTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // カスタマイズ

        // アイコンの色
        UITabBar.appearance().tintColor = UIColor(red: 255/255, green: 233/255, blue: 51/255, alpha: 1.0) // yellow

        // 背景色
        UITabBar.appearance().barTintColor = UIColor(red: 66/255, green: 74/255, blue: 93/255, alpha: 1.0) // grey black


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

7. 確認してみる

7.png

72
74
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
72
74