我有一个带3个孩子的TabViewController(2个TableViewControllers和一个带Label和TextView的ViewController)
我已经向导航中添加了一个RightBarButtonItem,但问题是Bar Button没有触发..
经过一些实验后,我注意到只有当所选视图是ViewController时,并且只有在编辑TextView时,才会触发条形按钮。 如果TextView已完成编辑,或者所选视图是TableViewControllers之一,则Bar Button不会触发
这是我的TabViewController类
class InfoTabViewController: UITabBarController, UITabBarControllerDelegate {
var index: Int?
var rightBarItem: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
// MARK: RightBarButtonItem
rightBarItem = UIBarButtonItem()
rightBarItem!.style = .Plain
rightBarItem!.action = #selector(self.rightBarItemSelected)
self.navigationItem.rightBarButtonItem = rightBarItem
self.delegate = self
}
override func viewDidAppear(animated: Bool) {
// MARK: RightBarButtonItem
editRightBarItem()
}
//Useless, fires before the tabbar item is selected not after... go to TabBarController instead
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
//print(self.selectedViewController?.title)
}
// UITabBarControllerDelegate fires after the tabbar item is selected, good one
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
editRightBarItem()
}
// MARK: RightBarButtonItem
func editRightBarItem() {
if let title = self.selectedViewController?.title {
switch title {
case "Tab Investigations":
rightBarItem!.title = "Add"
//rightBarItem!.enabled = true
break
case "Tab Treatment":
rightBarItem!.title = "Add"
//rightBarItem!.enabled = true
break
case "Tab Images":
rightBarItem!.title = "Add"
//rightBarItem!.enabled = true
break
case "Tab Notes":
rightBarItem!.title = "Save"
//rightBarItem!.enabled = true
break
default:
break
}
}
}
// MARK: RightBarButtonItem
func rightBarItemSelected() {
print("right bar item selected")
if let title = self.selectedViewController?.title {
print(title)
switch title {
case "Tab Investigations":
getInput(title, title: "New Test", message: "Insert Name and Value")
break
case "Tab Treatment":
getInput(title, title: "New Drug", message: "Insert Name and Dose")
break
case "Tab Images":
// do something
break
case "Tab Notes":
let view = self.viewControllers![0] as! NotesViewController
Patient.lstPatients[index!].history = view.textboxNotes.text
view.textboxNotes.endEditing(true)
//getInput("Add new test", message: "Insert name and value", viewTitle: self.selectedViewController!.title!)
break
default:
break
}
}
}
答案 0 :(得分:2)
按钮未触发的原因 - 您忘记设置target
。以下是文档中的一些词语:
weak var target: AnyObject? { get set }
该对象 选择项目时接收操作。如果为零,则为动作 消息被传递到响应者链,在那里它可以被处理 实现与选择器所对应的方法对应的任何对象 动作属性。默认值为nil。
所以,尝试添加
rightBarItem.target = self
或使用更宽的初始化程序
rightBarItem = UIBarButtonItem(title: "Add", style: .Plain, target: self, action: #selector(self.rightBarItemSelected))