LoginSignup
1
3

【Swift】ナビゲーションバーの右に閉じるボタンを設置

Last updated at Posted at 2021-10-22

Swiftでナビゲーションバーの右上に閉じるボタンを設置する方法。

//ボタンの実装
let next = NextViewController()
next.navigationItem.rightBarButtonItem = {
    let btn = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(self.onPressClose(_:)))
    return btn
}()
let nav = UINavigationController(rootViewController: next)
self.present(nav, animated: true, completion: nil)

次にボタンが押された時に処理されるonPressCloseの中身を実装。

//閉じる処理を書いた関数
@objc func onPressClose(_ sender : Any){
    self.dismiss(animated: true, completion: nil)
}

barButtonSystemItem: .closeは標準で搭載されているものから選べる。

close以外の種類を選びたい方は以下の記事がおすすめ。

Swiftのお役立ち情報

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