我有一個BarButtonItem我想添加到我的應用程序中的每個ViewController。我怎樣才能做到這一點,而不必將按鈕創建代碼和動作函數複製/粘貼到每個ViewController中?我更喜歡可重用性,而不是在每個ViewController中都有相同的代碼。Swift 3 - 添加BarButtonItem到NavigationBar在每個ViewController不重複代碼
按鈕代碼:
// Settings button
let btn = UIButton(type: .custom)
btn.setImage(UIImage(named: "icon-settings"), for: .normal)
btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
btn.addTarget(self, action: #selector(showSettings(sender:)), for: .touchUpInside)
let settingsBtn = UIBarButtonItem(customView: btn)
self.navigationItem.setRightBarButton(settingsBtn, animated: false)
行動:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "SettingsVC") as! SettingsViewController
self.navigationController?.show(vc, sender: self)
我試圖將此代碼添加到一個單獨的實用工具類,但因爲有你不能從它進行SEGUE如果在Utility類中聲明,則無法從操作函數訪問按鈕的父級ViewController。我也嘗試繼承UINavigationController並將其分配給Storyboard中的NavigationController,但它不起作用。
你需要子類'UIViewController',並讓你的每個視圖控制器的子類* *子類 – Paulw11