[Swift]ナビゲーションバーの色を変更する

Swiftでナビゲーションバーの色を変更するTipsをご紹介します。

実行環境

  • Xcode7.1.1
  • OSX Yosemite バージョン10.10.5

AppDelegateで変更する場合

ナビゲーションバーのアイテムの色、背景色、タイトル文字色を変更したい場合は、AppDelegate.swiftの```

  • application:didFinishLaunchingWithOptions:```
    メソッドで以下のような指定をします。
//AppDelegate.swift

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        //ナビゲーションアイテムの色を変更
        UINavigationBar.appearance().tintColor = UIColor.redColor()
        //ナビゲーションバーの背景を変更
        UINavigationBar.appearance().barTintColor = UIColor.yellowColor()
        //ナビゲーションのタイトル文字列の色を変更
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.greenColor()]
        
        return true
    }

結果こうなる

navigation1

UIViewControllerで変更する場合

UIAppearanceプロトコルはwindowに挿入されるまえに指定することへ変更が効く。逆に言えばwindowに挿入されたあとにメソッドを呼び出しても色が変更されない

-application:didFinishLaunchingWithOptions:ではViewがwindowに挿入される前に呼び出されるので色の変更が効いた。
しかしUIViewControllerでUIAppearanceを呼び出しても、Viewがwindowに挿入が完了しているので色の変更がされない

UIViewControllerでナビゲーションバーの色を変更したい場合は、self.navigationController?のプロパティを変更する

//ViewController.swift

     override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //バー背景色
        self.navigationController?.navigationBar.barTintColor = UIColor.yellowColor()
        
        //バーアイテムカラー
        self.navigationController?.navigationBar.tintColor = UIColor.redColor()
        
        //ナビゲーションタイトル文字列の変更
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.greenColor()]
        
    }

参考