我有一个类型的 segue:Show Detail
链接到 Master View Controller 的 UITableViewCell
。在 viewDidLoad
的 Detail View Controller 中,我尝试覆盖 leftBarButtonItem
:
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon-menu"), style: .Plain, target: self, action: Selector("menuButtonTapped:"))
我调用的方法如下:
func menuButtonTapped(sender: UIBarButtonItem) {
navigationController?.popViewControllerAnimated(true)
}
但它不想工作。调用方法,但没有弹出操作,因为 navigationController
在 viewControllers
数组中只有一个 Controller 。当我不尝试覆盖 leftBarButtonItem
时,一切都很好,有一个默认的 Back 按钮,当我点击它时, Controller 从堆栈中弹出。出了什么问题?
最佳答案
鉴于问题中使用了Master View Controller 和Detail View Controller,我假设您使用的是UISplitViewController
。如果是这种情况,您的 Detail View Controller 将不会在您的 UINavigationController
中找到。你一定要检查Apple's docs在 UISplitViewController
上。
其次,当您在表格 View 中选择一个单元格时出现的 UIBarButtonItem
是由 UISplitViewController
自动生成的。我发布的上一个链接中解释了此按钮背后的逻辑。如果您只需要自定义其外观,我建议您查看 Apple's docs在这件事上也是如此。替换 UIBarButtonItem
似乎对您要实现的目标来说有点矫枉过正。
此外,我不太确定您为什么需要覆盖按钮的操作。因为这是一个 UISplitViewController
,所以这个按钮不会在所有可能的界面上都可见。所以你的自定义操作并不总是会被执行。您不能在 Detail View Controller 的 viewWillDisappear:
或 viewDidDisappear:
方法上执行自定义代码吗?
最后,如果上述解决方案仍然不能满足您的需求,您可以执行以下操作:
class DetailViewController: UIViewController: UISplitViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.splitViewController?.delegate = self
}
func splitViewController(svc: UISplitViewController, willChangeToDisplayMode displayMode: UISplitViewControllerDisplayMode) {
if displayMode == .PrimaryHidden {
self.previousButton = navigationItem.leftBarButtonItem
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon-menu"), style: .Plain, target: self, action: Selector("menuButtonTapped:"))
}
}
private var previousButton: UIBarButtonItem?
@objc func menuButtonTapped(sender: UIBarButtonItem) {
//your custom code
if let target = self.previousButton?.target as? NSObject {
target.performSelector(self.previousButton!.action)
}
}
}
我还没有测试过这个,但我想你会明白的。
此外:请注意,这有点老套,我只建议将此作为最后的资源。
关于ios - 如何从通过 Show Detail segue 推送的堆栈中手动弹出 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34391633/