以下是一段无效的代码:
class Person {
static fun addBtn(cName:UIViewController)
{
let rightBtn = UIBarButtonItem.init(title: "Right", style: .Plain, target: UIBarButtonItem.self, action:#selector(UIBarButtonItem.self.newMenuTapped(_:)))
cName.navigationItem.rightBarButtonItem = rightBtn
}
}
extension UIBarButtonItem
{
func newMenuTapped(sender: UIBarButtonItem)
{
print("Tapped")
}
}
崩溃并出现此错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: unrecognized selector sent to class 0x14c830
有人可以指导我做错了什么吗?谢谢。
最佳答案
像这样为 UIViewController
创建一个扩展:
extension UIViewController {
func addButton() {
let button = UIBarButtonItem(title: "Right", style: .Plain, target: self, action: #selector(self.rightButtonPressed(_:)))
self.navigationItem.setRightBarButtonItem(button, animated: false)
}
func rightButtonPressed(sender: UIBarButtonItem) {
print("tapped")
}
}
然后在所有要实现按钮的 View Controller 中调用 self.addButton()
。
关于ios - 需要在所有 VC 中添加通用的 UIBarButtonItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38394918/