どういうことか
こういうことがやりたい
文字を書くだけであれば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")!)
// 中略
以上です(´・ω・`)