LoginSignup
2
2

More than 3 years have passed since last update.

[Swift]オシャレなNavigationBar(色・フォント・アイテムのアレンジ)の作成(画面ごとに設定)

Last updated at Posted at 2020-06-13

本記事では、オシャレなNavigationBarの作成の仕方(色・フォント・アイテムのアレンジの仕方)を紹介します!
とても簡単に実装可能なのでぜひ試してみてください!

Before

スクリーンショット 2020-06-13 20.23.49.png

After

スクリーンショット 2020-06-13 21.38.39.png

上記のように、NavigationBarをアレンジするだけでオシャレになりましたね!
※ 本記事では、画面ごとにNavigationBarをアレンジしていますが、全体を同じデザインでアレンジしたい場合は下記の記事を参考にしてみてください。
[Swift]オシャレなNavigationBar(色・フォント・アイテムのアレンジ)の作成

では、下記のように実装していきましょう!

1. Main.storyboardの準備

まず、Main.storyboardに下記の写真のようにNavigationControllerを作成します。
これで、Beforeの部分は完成です!
スクリーンショット 2020-06-13 3.08.27.png

2. それぞれのViewController.swiftにデザインをアレンジするためのコーディング

それでは、Afterのようにオシャレにデザインしていきましょう!
とても簡単で、画面ごと(ViewController.swiftごと)に下記のように、viewWillAppearにコードを書くことで実装できます!

下記のコードはAfter画面ごとに設定1にあたります。

ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        self.navigationItem.title = "画面ごとに設定1"

        // ナビゲーションバーの背景色
        self.navigationController?.navigationBar.barTintColor = UIColor.yellow

        self.navigationController?.navigationBar.titleTextAttributes =
            // フォントカラー
            [NSAttributedString.Key.foregroundColor: UIColor.blue,
             // フォントの種類
                NSAttributedString.Key.font: UIFont(name: "Times New Roman",
                    // フォントサイズ
                    size: 15)!]

        // ナビゲーションバー上のアイテムの色
        self.navigationController?.navigationBar.tintColor = UIColor.black
    }
}

下記のコードはAfter画面ごとに設定2にあたります。

SecondViewController.swift
import UIKit

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        self.navigationItem.title = "画面ごとに設定2"

        // ナビゲーションバーの背景色
        self.navigationController?.navigationBar.barTintColor = UIColor.cyan

        self.navigationController?.navigationBar.titleTextAttributes =
            // フォントカラー
            [NSAttributedString.Key.foregroundColor: UIColor.purple,
             // フォントの種類
                NSAttributedString.Key.font: UIFont(name: "Times New Roman",
                    // フォントサイズ
                    size: 30)!]

        // ナビゲーションバー上のアイテムの色
        self.navigationController?.navigationBar.tintColor = UIColor.red
    }
}

参考

NavigationBarを全て同じデザインでアレンジしたい場合はこちらの記事を参考にしてみてください。

2
2
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
2
2