Swift中的条件转场

12

我想在我的应用程序中添加一个“连接”按钮。当您点击它时,如果您有正确的登录信息,它将打开一个新页面。

但我读到我们不能撤销Segue,我想我需要手动调用它。你有什么想法吗?

我还尝试了这样的代码:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject) {
    if checkLog == true
    {
     //finish   
    }
    else
   {
    // undo
   }
}

@IBAction func ConexTAP(sender: UIButton)
{
 //check login
}
2个回答

17

您可以在ViewController中使用以下方法进行凭据检查:

func shouldPerformSegueWithIdentifier(_ identifier: String!,
                              sender: AnyObject!) -> Bool

作为替代方案,您可以将UIButton绑定到视图控制器中的操作,然后在此执行检查,最后通过代码触发segue。


谢谢,它起作用了!你能告诉我如何通过代码触发一个segue吗? - 1L30
4
使用 performSegueWithIdentifier("segueName", sender: self)。该方法用于执行标识符为"segueName"的Segue转场,并将当前视图控制器作为发送方(sender)传递给目标视图控制器。 - mxb
2
@mxb 按照您的方法,您仍会在Storyboard上创建(控制+拖动)从按钮到下一个场景的segue“segueName”吗?如果是这样,segue是否会在单击按钮时自动触发,而无需检查凭据? - user3207158

7
在Swift中,您可以按照以下步骤进行操作:
第1步:从ViewControllerA到ViewControllerB插入segue。 segue应该从ViewControllerA本身开始,而不是从任何控件(如按钮)开始。
第2步:在storyboard中为segue提供唯一标识符。例如:seageFromAtoB
第3步:在您的ViewControllerforA.swift文件中编写以下内容:
if(condition == true) {
    self.performSegueWithIdentifier("seageFromAtoB", sender: self)
}

如果您在其他线程中执行某些任务,则使用performSegueWithIdentifier可能会抛出异常。

如果您遇到此错误,则应使用以下内容:

if(condition==true){
      NSOperationQueue.mainQueue().addOperationWithBlock {
           self.performSegueWithIdentifier("seageFromAtoB", sender: self)
      }
}

这将根据特定条件从ViewControllerA执行跳转到ViewControllerB。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接