【问题标题】:ShouldPerformSegue in iOS and macOSiOS 和 macOS 中的 ShouldPerformSegue
【发布时间】:2020-05-06 00:54:39
【问题描述】:

我只想在有条件的情况下进行转场。例如 textField 中有文本。

首先,我在情节提要中将视图控制器的图标连接到第二个视图控制器。然后我在 ViewController 中有按钮。

在 iOS 中这很好用,只有在 textField1 中有文本时才会进行转场:

 @IBAction func goTo2(_ sender: UIButton) {
        let str: String? = textField1.text
        if str!.isEmpty {
            print ("text field is empty. Do not do the segue")
        }
        else {
            print ("Do the segue")
            performSegue(withIdentifier: "segueTo2", sender: self)
        }
}

在 macOS 中,如果我这样做,它总是会产生 segue,即使 textFiel1 中没有文本。所以我必须添加 shouldPerformSegue。

在 macOS 中这很好用:

@IBAction func goTo2(_ sender: Any) {
    performSegue(withIdentifier: "segueTo2", sender: self)
}

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {     
    let str: String? = textField1.stringValue
    if str!.isEmpty {
        print ("it is empty")
        return false
    }
    else {
        return true
    }     
}

在 Apple 文档中,他们说 shouldPerformSegue 适用于 iOS 和 mac。

我所描述的效果很好,但我不明白为什么 iOS 和 maOS 之间存在差异。这是最好的方法吗?谁能解释为什么?

【问题讨论】:

  • 您在 iOS 版本中以编程方式执行 segue,而在 MacOS 版本中您使用的是 shouldPerformSegue 在 iOS 中也存在 shouldPerformSegue。您处理每个操作系统的方式不同,任何一种方法都适用于任何一个系统。
  • 正如您在previous question 中已经提到的那样,当您要执行 segue 手动 时,实际上(在 macOS 和 iOS 中)覆盖该方法是没有意义的,无论不同的行为

标签: ios swift macos


【解决方案1】:

您有两种方法可以检查是否应该根据您的代码进行 segue。

Segue 方法 #1(iOS 和 MacOS)

@IBAction func goTo2(_ sender: UIButton) {   
        if !textField1.text.isEmpty {
            performSegue(withIdentifier: "segueTo2", sender: self)   
        }
        print ("text field is empty. Do not do the segue")
}

Segue 方法 #2(iOS 和 MacOS)

@IBAction func goTo2(_ sender: Any) {
    performSegue(withIdentifier: "segueTo2", sender: self)
}

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {     
    if !textField1.stringValue.isEmpty {
        return true
    }
    print ("it is empty")
    return false  
}

如您所见,Method #1Method #2 似乎都在做同样的事情,但实际上并没有。在Method #1 中,您在进行转场之前检查它是否为空。在Method #2 中,您正在检查是否应该在调用segue 之后进行segue。

任何一种方法都有效,并且有很多变通方法。最大的不同是使用Method #1 会迫使您错过某些运行其他方法(例如prepareForSegue(...))的机会,这意味着您可能会错过生命周期事件。但是,您仍然可以使用prepareForSegue(...),只是在触发 segue 之前您不能使用 is。

简而言之,对于您的使用,基于当前代码,使用Method #2 根本没有意义。但是,如果您需要在 segue 之后执行某些功能,但如果不满足某些条件仍然阻止 segue 发生,那么您将使用Method #2,但即使这样也可以有一个解决方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2017-04-06
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多