我想只有在有一些条件的情况下才进行转场。例如,在textField中有文本。
首先,我在storyboard中建立了从View Controller的图标到Second View Controller的连接。然后我在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中,如果我做同样的事情,它总是会进行切换,同样是在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
}
}
在苹果的文档中,他们说shouldPerformSegue适用于iOS和mac.
我所描述的工作很好,但我不明白为什么iOS和maOS之间的差异。谁能解释一下为什么?
你有两种方法来检查是否应该根据你的代码进行切换。
@IBAction func goTo2(_ sender: UIButton) {
if !textField1.text.isEmpty {
performSegue(withIdentifier: "segueTo2", sender: self)
}
print ("text field is empty. Do not do the segue")
}
@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 #1
和 Method #2
看似在做同样的事情,但其实不然。在 Method #1
你在做转场之前检查它是否为空。在 Method #2
你是在调用segue之后检查是否应该进行segue。
两种方法都可以用,而且有很多变通的方法。最大的区别是在调用 Method #1
迫使你错过了运行其他方法的某些机会,如 prepareForSegue(...)
这意味着你可能会错过一个生命周期事件。然而,您仍然可以使用 prepareForSegue(...)
只是你不能在转场被触发之前使用is。
简而言之,根据目前的代码,对于你的用途来说,在触发转场之前使用 Method #2
根本不可能。然而,如果你需要在segue之后执行一些功能,但如果某些条件没有得到满足,你仍然需要阻止segue的发生,那么你会使用 Method #2
但即使是这样也可以有一个变通的办法。