ios Swift prepareForSegue 取消

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28883050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:07:21  来源:igfitidea点击:

Swift prepareForSegue cancel

iosswift

提问by Triton Man

I'm trying to implement a login screen, when login is clicked it does the segue "login".

我正在尝试实现一个登录屏幕,当点击登录时,它会执行“登录”。

I added a prepareForSegue() override to try to cancel it if the login fails but I don't see any method to cancel the segue if there is a failure.

我添加了一个 prepareForSegue() 覆盖来尝试在登录失败时取消它,但我没有看到任何方法来取消如果出现失败的 segue。

What is the best way to do this?

做这个的最好方式是什么?

回答by Greg

You should override shouldPerformSegueWithIdentifierand return false if login failed:

shouldPerformSegueWithIdentifier如果登录失败,您应该覆盖并返回 false:

override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
    if let ident = identifier {
        if ident == "YourIdentifier" {
             if loginSuccess != true {
                  return false
             }
         }
     }
     return true
}

UPDATED FOR SWIFT 3Swift 3 method is now called shouldPerformSegue

更新 SWIFT 3Swift 3 方法现在被调用shouldPerformSegue

    override func shouldPerformSegue(withIdentifier identifier: String?, sender: Any?) -> Bool {
    if let ident = identifier {
        if ident == "YourIdentifier" {
            if loginSuccess != true {
                return false
            }
        }
    }
    return true
}

// Extended

// 扩展

If you programmatically call performSegueWithIdentifier this method will not be called but it's not need for that, you can call it just your login success, otherwise ignore it:

如果您以编程方式调用 performSegueWithIdentifier,则不会调用此方法,但不需要,您可以仅在登录成功时调用它,否则忽略它:

if loginSuccess {
    performSegueWithIdentifier("login", sender: nil)
}

回答by Aleksi Sj?berg

You could do a segue from a View Controller, not from a specified button. You do it by ctrl-dragging from the yellow button at top of the VC on storyboard. Remember to give the segue an identifier!

您可以从 View Controller 执行 segue,而不是从指定的按钮。您可以通过从故事板 VC 顶部的黄色按钮按住 ctrl 拖动来完成此操作。记得给 segue 一个标识符!

Then you can create an IBAction function from login button and do performSegueWithIdentifier. It should look something like this:

然后你可以从登录按钮创建一个 IBAction 函数并执行 performSegueWithIdentifier。它应该是这样的:

@IBAction func loginButtonTapped(sender: UIButton) {
    if loginSuccess {
        performSegue(withIdentifier: "login", sender: nil)
    }
}

then, in prepare(:), you could do additional setup for the segue, as it will be called before the actual segue takes place.

然后,在 prepare(:) 中,您可以为 segue 进行额外的设置,因为它将在实际 segue 发生之前被调用。