从Swift中的导航后退按钮展开segue [英] Unwind segue from navigation back button in Swift

查看:102
本文介绍了从Swift中的导航后退按钮展开segue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设置屏幕,因为我有一个表格单元格。通过单击我进入另一个屏幕,用户可以选择一个选项,并在按下后退按钮时将其返回到上一个视图控制器。

I have a settings screen, in that I have a table cell. By clicking on that I take to another screen where user can choose an option and I want it back in the previous view controller when back button is pressed.

我可以放置一个自定义栏按钮项,但我想使用导航栏中的后退按钮返回到父视图控制器,而不是在视图上使用自定义按钮。

I can put a custom bar button item, but I want to return to the parent view controller using the back button in the navigation bar rather than with a custom button on the view.

我似乎无法覆盖导航后退按钮,将其指向我的展开segue操作,因为后面故事板上没有出现按钮,我无法将绿色的退出按钮拖到它上面

I don't seem to be able to override the navigation back button to point it down to my unwind segue action and since the back button doesn't appear on the storyboard, I cant drag the green Exit button to it

是否可以使用后退按钮展开推送segue?

Is it possible to unwind a push segue with the back button?

推荐答案

这是我的解决方案,基于Blankarsch的Objective-C代码到此StackOverflow问题:如何捕获后退按钮事件

Here's my solution, based on Objective-C code from Blankarsch to this StackOverflow question: How to trap the back button event

将此代码放入View Controller中,您想要捕获Back按钮调用:

Put this code inside the View Controller you want to trap the Back button call from:

override func didMoveToParentViewController(parent: UIViewController?) {
    if (!(parent?.isEqual(self.parentViewController) ?? false)) {
        println("Back Button Pressed!")
    }
}

在if块的内部,处理你需要传回的任何内容。您还需要有一个返回调用视图控制器的引用,因为此时很可能parent和self.parentViewController都是nil,因此您无法导航View Controller树。

Inside of the if block, handle whatever you need to pass back. You'll also need to have a reference back to calling view controller as at this point most likely both parent and self.parentViewController are nil, so you can't navigate the View Controller tree.

此外,您可以通过简单地检查父项为nil来逃避,因为我没有找到按下后退按钮不会导致父项为零的情况。所以这样的事情更简洁:

Also, you might be able to get away with simply checking parent for nil as I haven't found a case where pressing the back button didn't result in parent being nil. So something like this is a bit more concise:

override func didMoveToParentViewController(parent: UIViewController?) {
    if (parent == nil) {
        println("Back Button Pressed!")
    }
}

但我不能保证每次都会有效。

But I can't guarantee that will work every time.

Andrew

这篇关于从Swift中的导航后退按钮展开segue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆