LoginSignup
0

More than 5 years have passed since last update.

[iOS tips] UINavigationControllerのbarButtonItemsを追加する時はtopViewControllerかどうかを意識すべし

Posted at

遷移した先のnavigationControllerの右側にボタンを追加しようとして以下のコードを試しても全然ボタンが現れなかった。

uploadButton = UIBarButtonItem(title: "Upload", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.upload(images:)))
navigationController.navigationItem.rightBarButtonItem = uploadButton

しかし、以下のコードで実現できた。

uploadButton = UIBarButtonItem(title: "Upload", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.upload(images:)))
navigationController.topViewController?.navigationItem.rightBarButtonItem = uploadButton

ドキュメントを見るとしっかり書いてある。

 var rightBarButtonItem: UIBarButtonItem?
A custom bar button item displayed on the right (or trailing) edge of the navigation bar **when the receiver is the top navigation item.**

ドキュメントはしっかり読みましょう。

cf. https://developer.apple.com/reference/uikit/uinavigationitem/1624957-rightbarbuttonitem

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
0