【发布时间】: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 中)覆盖该方法是没有意义的,无论不同的行为