我最近学习使用xCode编写Swift代码。我创建了一个简单的故事板,并试图比较文本域内的文本字段值。
这是我的代码:
var numberone = 0
var numbertwo = 0
var answerstring :String = ""
var answerint :Int = 0
var userInput :String = ""
@IBAction func userTextField(_ sender: UITextField) {
numberone = randomInt(min: 1, max: 9)
numbertwo = randomInt(min: 1, max: 9)
questionLabel.text = "\(numberone) + \(numbertwo)"
answerint = numberone + numbertwo
answerstring = "\(answerint)"
if userTextField.text! = "\(answerstring)" {
questionResponse.text! = "Correct!"
} else {
questionResponse.text! = "Incorrect. The answer was \(answerint)."
}
错误发生在 userTextField.text!上,并显示:
Value of type '(UITextField) -> ()' has no member 'text'
答案 0 :(得分:0)
您正在比较userTextField
这是方法名称,而应该是sender
:
@IBAction func userTextField(_ sender: UITextField) {
numberone = randomInt(min: 1, max: 9)
numbertwo = randomInt(min: 1, max: 9)
questionLabel.text = "\(numberone) + \(numbertwo)"
answerint = numberone + numbertwo
answerstring = "\(answerint)"
// here is the change, 'sender' instead of 'userTextField':
if sender.text! = "\(answerstring)" {
questionResponse.text! = "Correct!"
} else {
questionResponse.text! = "Incorrect. The answer was \(answerint)."
}
}
答案 1 :(得分:0)
您必须从@IBAction收到的发件人处获取文本字段。
这很简单。发件人是您想要的文本字段。
首先:
if sender.text! == "\(yourVariable)" {
//do something
}else{
//do someting
}
记得使用double equals进行比较。如果您只使用一个,它将设置文本字段的值。