目的
ナビゲーションバーに関する設定
- ナビゲーションバーの右側に色付きアイコンボタンを設定
- ナビゲーションバーの高さを取得
の2つのメモです。
環境
- Xcode 11
- Swift 5.1
ナビゲーションについて
ナビゲーションって書いてますが、Navigation Controller
のことです。
以下の様にただNavigation Controllerを設定しただけです。
ナビゲーションバーの右側に色付きアイコンボタンを設定
まず、Imageはこんな青色画像を設定しました。
そしてコードのみで
ナビゲーションバーの右側に、色を指定した画像アイコンのボタンを設定します。
以下のようにしました。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let button = UIButton(type: .system)
button.frame = CGRect(x: 0.0, y: 0.0, width: 60, height: 60)//サイズ
button.setImage(#imageLiteral(resourceName: "Image"), for: .normal)//画像設定
button.tintColor = #colorLiteral(red: 0.521568656, green: 0.1098039225, blue: 0.05098039284, alpha: 1)
button.addTarget(self, action: #selector(self.rightButtonPress), for: UIControl.Event.touchUpInside)
let barItem = UIBarButtonItem(customView: button)
//コードでAuto Layout設定をする
let currWidth = barItem.customView?.widthAnchor.constraint(equalToConstant:38)
currWidth?.isActive = true
let currHeight = barItem.customView?.heightAnchor.constraint(equalToConstant: 38)
currHeight?.isActive = true
self.navigationItem.rightBarButtonItem = barItem
}
@objc
func rightButtonPress() {
//~~
}
以下のようにアイコンのもともとの色とは違うコード上で設定した色になりました。
ナビゲーションバーの高さを取得
ナビゲーションバーの高さを取得するコード。
iOS11からラージタイトルナビゲーションバーとか出てきたし、44ptなどと固定でやるのは危険
let navigationBarHeight = self.navigationController?.navigationBar.frame.size.height ?? 0
print(navigationBarHeight)
->44.0
メモは以上です。