我的目的是在所有文本字段都已填充的情况下运行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
    }

最佳答案

尝试以下解决方案:

@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
}

10-04 21:58