Swift-在条件下执行performSegue

时间:2019-04-20 16:55:22

标签: ios swift xcode

我的意图是仅在所有文本字段均已填充的情况下运行performSegue。如果不是,则该按钮不起作用-确切地说,不应执行performSegue

我的方法是将performSegue放在if语句中,但是无论如何,尽管两个字段均为空,它还是被忽略了,无论如何都在执行performSegue。还有另一种更成功的方法吗?

@IBAction func buttonAdd(_ sender: Any) {
        if (addKmInput.text! != "" && addPriceInput.text != "") {
            ...
            performSegue(withIdentifier: "goBackToSecond", sender: self)
        }
    }
@IBOutlet weak var addKmInput: UITextField!
@IBOutlet weak var addPriceInput: UITextField!

新版本:

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

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        switch identifier {
        case "goBackToSecond":
            return shouldGoBackToSecond()
        default:
            return true
        }
    }

func shouldGoBackToSecond() -> Bool {
        guard let kmInput = addKmInput.text, let priceInput = addPriceInput.text else { return false }
        return !kmInput.isEmpty && !priceInput.isEmpty
    }

2 个答案:

答案 0 :(得分:1)

尝试以下解决方案:

@IBAction func buttonAdd(_ sender: Any) {
    if shouldGoBackToSecond() {
        performSegue(withIdentifier: "goBackToSecond", sender: self)
    }
}

func shouldGoBackToSecond() -> Bool {
    guard let kmInput = addKmInput.text, let priceInput = addPriceInput.text else { return false }
    return !kmInput.isEmpty && !priceInput.isEmpty
}

答案 1 :(得分:0)

使用str.isEmpty检查textField中的字符串是否为空:

if let t1 = addKmInput?.text, let t2 = addPriceInput?.text, !t1.isEmpty, !t2.isEmpty {
        ...
        performSegue(withIdentifier: "goBackToSecond", sender: self)
}

,理想情况下,您应该使用此委托来拒绝执行segue操作:

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { 
    return true //return true/false conditionally. returning false will prevent segue performance. 
}