我有一个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