うみとさとみの日常

シーズー犬うみと飼い主Satomiが楽しく生活してみます

NavigationItemをNavigationBarの右側にコードで設定する方法

虫眼鏡アイコンを追加してみます

overrided func viewDidLoad() {
  // show search button and set action
  var rightSearchBarButtonItem:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "searchButtonTapped")
  // add the button to navigationBar
  self.navigationItem.setRightBarButtonItems([rightSearchBarButtonItem], animated: true)
}

複数を右側に追加してみます

overrided func viewDidLoad() {
  var rightFooBarButtonItem:UIBarButtonItem = UIBarButtonItem(title: "Foo", style: UIBarButtonItemStyle.Plain, target: self, action: "fooButtonTapped")

  var rightSearchBarButtonItem:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "searchButtonTapped:")

  self.navigationItem.setRightBarButtonItems([rightAddBarButtonItem,rightSearchBarButtonItem], animated: true)
}

こちらも忘れずに

func fooButtonTapped(){

}

func searchButtonTapped(){

}