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のお役立ち情報