Swift 3 - 添加BarButtonItem到NavigationBar在每个ViewController不重复代码
我有一个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,但它不起作用。
您可以通过添加BaseViewController
并在其中插入代码来完成此操作。之后,在你的navigationController的rootviewController上,你只需从这个BaseViewController
扩展。这样做,并且在该函数中调用super
它将始终使该代码可用,并且不需要在每个视图控制器中重复该代码。
import UIKit
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 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)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
,然后在视图控制器,你只是延长BaseViewController
class ViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Button should already appear here
}
注意的ViewController应该是你的根视图控制器。
这是一个好主意,我会仔细检查它是我批准的,非常感谢你! –
你需要子类'UIViewController',并让你的每个视图控制器的子类* *子类 – Paulw11