ios - 如何从通过 Show Detail segue 推送的堆栈中手动弹出 View Controller ?

标签 ios swift uiviewcontroller

我有一个类型的 segue:Show Detail 链接到 Master View ControllerUITableViewCell。在 viewDidLoadDetail 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)
}

但它不想工作。调用方法,但没有弹出操作,因为 navigationControllerviewControllers 数组中只有一个 Controller 。当我不尝试覆盖 leftBarButtonItem 时,一切都很好,有一个默认的 Back 按钮,当我点击它时, Controller 从堆栈中弹出。出了什么问题?

最佳答案

鉴于问题中使用了Master View ControllerDetail View Controller,我假设您使用的是UISplitViewController。如果是这种情况,您的 Detail View Controller 将不会在您的 UINavigationController 中找到。你一定要检查Apple's docsUISplitViewController 上。

其次,当您在表格 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/

相关文章:

ios - DSLCalendarView 重新加载

ios - 通过 ms-word 打开 Office 文档 :ofe on iPad

ios - 无法将 QLPreviewController 添加为 childViewController iOS10

ios - 是否无法在不构建 View 的情况下以编程方式创建 UIViewController?

swift - 如何从UIView调用presentViewController?

iphone - 如何检查请求地址和响应地址是否相同

ios - UITableView 添加 FooterView 按钮有时点击不执行操作

ios - 导航栏隐藏在 SwiftUI 中不起作用

swift - 如何通过prepareForSegue更改按钮的色调颜色

ios - 如何在 StoryBoard 中连接 UI Popover ViewController