LoginSignup
2
3

More than 3 years have passed since last update.

【Swift】NavigationBarのtitleを『文字列 + 画像』にする

Posted at

どういうことか

こういうことがやりたい

Simulator Screen Shot - iPhone 11 - 2021-03-05 at 15.02.26.png

文字を書くだけであればControllerに

title = "タイトル部分です"

と書くだけでいい。

実装する

extensionを使う。
Controllerの一番下にでも書こう。

ここでは文字を 太字 にする設定も書いている。
細かい設定はともかくコピペで書いてもイケる。

ViewController.swift
// 文字列とアイコン画像を並べたタイトルを作る
extension HomeViewController {
    func setTitle(_ title: String, andImage image: UIImage) {
        let titleLabel = UILabel()
        titleLabel.text = title
        titleLabel.font = UIFont.boldSystemFont(ofSize: 14)
        let imageView = UIImageView(image: image)
        let titleView = UIStackView(arrangedSubviews: [imageView, titleLabel])
        titleView.axis = .horizontal
        titleView.spacing = 10.0
        navigationItem.titleView = titleView
    }
}

そしたら viewDidLoad() 内でこのメソッドに必要な値を渡す。

ViewController.swift
    override func viewDidLoad() {
        super.viewDidLoad()

        // タイトルの文字列と画像の名前を渡す
        setTitle("タイトル部分です", andImage: UIImage(named: "user_icon")!)

        // 中略

以上です(´・ω・`)

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