LoginSignup
30
27

More than 5 years have passed since last update.

タブバーの高さと、文字の位置・大きさを変えて、文字だけのタブバーを作る

Last updated at Posted at 2015-12-30

デフォルトでは、タブバーはアイコンと小さな文字で構成されます。
アイコンを用意するのは面倒だし、文字だけでタブバーを作れないものかと思い立ち、実装してみました。

アイコンを使わないだけなら、画像を設定しなければ良いだけなのですが、それだけだと小さな文字がタブバー下部に配置されてしまいますよね。
文字を大きくして、タブバーの真ん中付近に配置したいです。また、文字だけにするとなると、デフォルトのタブバーではちょっと縦長過ぎますよね。なので高さも小さくしたいです。

実装方法

Swift 2.1です。

文字の位置と大きさを変える

タブバー上の各UITabBarItemが、文字の位置と大きさを持っています。アプリケーション内で使用されるタブバーは高々1つでしょうから、以下のようにしてまとめて変更してしまって良いと思います。
一行目で好きなフォントを割り当て、二行目で座標を変更しています。

UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Avenir-Medium", size: 14)!], forState: .Normal) // 好きなフォントを
UITabBarItem.appearance().titlePositionAdjustment = UIOffsetMake(0, -9)

これをTabBarViewControllerのviewDidLoadなり、AppDelegateのapplication:didFinishLaunchingWithOptionsなりに配置すれば良さそうです。

タブバーの高さを変える

描画されるタブバーの高さは、UITabBarのsizeThatFitsにより決まっているようです。なのでそれをoverrideして、適当な高さを与えて返すようにすることで、高さを変えることができます。


class TabBar: UITabBar {

    override func sizeThatFits(size: CGSize) -> CGSize {
        var size = super.sizeThatFits(size)
        size.height = 40
        return size
    }

}

サンプルコード

以下の例ではタブバーのViewControllerを適当なstoryboardから取得しています。

class TabBar: UITabBar {

    override func sizeThatFits(size: CGSize) -> CGSize {
        var size = super.sizeThatFits(size)
        size.height = 40
        return size
    }

}
class TabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        addTabBarItems()
        layoutTabBarItems()
    }

    func addTabBarItems() {
        addChildViewControllerWithStoryboardName("Timeline")
        childViewControllers.last?.tabBarItem = UITabBarItem(title: "Timeline", image: nil, tag: 1)
        addChildViewControllerWithStoryboardName("MyPage")
        childViewControllers.last?.tabBarItem = UITabBarItem(title: "MyPage", image: nil, tag: 2)
    }

    func addChildViewControllerWithStoryboardName(storyboardName: String) {
        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
        let vc = storyboard.instantiateInitialViewController()        
        addChildViewController(vc!)
    }

    func layoutTabBarItems() {
        tabBar.translucent = false
        tabBar.barTintColor = UIColor.lightOrangeColor()
        tabBar.tintColor = UIColor.deepGrayColor()

        UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Avenir-Medium", size: 14)!], forState: .Normal)
        UITabBarItem.appearance().titlePositionAdjustment = UIOffsetMake(0, -9)
    }

}

sample.png

30
27
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
30
27