我有一个嵌入导航控制器的MainViewController,如下所示:
在MainViewController.swift中,我以编程方式添加了两个UIBarButtonItem(左和右):
class MainViewController: UIViewController {
let rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(onRightClick))
let leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(onLeftClick))
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = rightButton
navigationItem.leftBarButtonItem = leftButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc func onRightClick() {
print("[Main] Right Click")
}
@objc func onLeftClick() {
print("[Main] Left Click")
}
}
按钮确实显示在屏幕上,但有趣的是,每当我按下向左或向右按钮时,选择器函数onLeftClick
和onRightClick
都不会被调用。我有什么办法让它有效吗?我正在使用Xcode 9.3。
答案 0 :(得分:6)
尝试使用内部范围
override func viewDidLoad() {
super.viewDidLoad()
let rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(self.onRightLeftClick(_ :)))
rightButton.tag = 1
let leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(self.onRightLeftClick(_ :)))
rightButton.tag = 2
self.navigationItem.rightBarButtonItem = rightButton
self.navigationItem.leftBarButtonItem = leftButton
}
将操作处理为
func onRightLeftClick(_ sender: UIBarButtonItem){
if sender.tag == 1{
// rightButton action
}else{
// leftButton action
}
}
答案 1 :(得分:1)
您也可以只将lazy
关键字添加到rightButton和leftButton类属性中。这样,UIBarButtonItem
不会实例化(并且动作选择器也不会尝试解析),除非它们在类中使用。通过这种方式,您可以在类中的任何位置使用barButtonItems(不仅在声明它们的函数中)。
lazy var rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: #selector(onRightClick))
lazy var leftButton = UIBarButtonItem(title: "Left", style: .plain, target: self, action: #selector(onLeftClick))