2016-11-20 137 views
0

我最近一直在學習使用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

'userTextField'是一個*函數*(或*方法*)。 'sender'是(引用)文本字段... –

回答

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)." 
    } 
} 
0

你必須得到你收到你發送的文本框@ IBAction爲。

這很簡單。發件人是您想要的文本框。

第一:

if sender.text! == "\(yourVariable)" { 
     //do something 
    }else{ 
     //do someting 
    } 

記得用雙等於比較。如果只使用一個,它將設置文本字段的值。