swift检测正确的文本字段以添加属性

时间:2016-03-31 06:23:27

标签: xcode swift loops

我正在写一个输入文本测验应用程序,我有一个Int数组我可以存储如果答案是正确与否0或1而且我有3个文本字段我写的答案,我想根据答案变量将文本字段背景颜色更改为红色或绿色,如果索引变量1将颜色更改为绿色,如果为0则将颜色更改为红色..这就是我所拥有的

@IBOutlet var textField1: UITextField!
@IBOutlet var textField2: UITextField!
@IBOutlet var textField3: UITextField!


//change int to 1 if answer was correct (3, ea for each textfield)
var answers = [0,0,0]   


@IBAction func button(sender: AnyObject) {

    for (index, answer) in goodAnswers.enumerate() {

        print (answer)

        if answer != 0 {

            print ("ok")

        } else {

            print("not ok")
        }       

    }        
}

谢谢!

1 个答案:

答案 0 :(得分:0)

你需要这样的东西:

 var goodAnswers = ["One", "Two", "Three"]
 var textFields:[Int:UITextField]!

 override func viewDidLoad() {
    super.viewDidLoad()
    self.textFields = [0:textField, 1:textField2]
 }

@IBAction func btnClick(sender: AnyObject) {
    for(index, answer) in goodAnswers.enumerate() {
        if textFields[index]?.text == answer {
            textFields[index]?.backgroundColor = UIColor.greenColor()
        }
        else {
            textFields[index]?.backgroundColor = UIColor.redColor()
        }
    }
}

更新:

如果您想获得其他好的答案,只需将代码更改为:

声明新属性:

var collectionOfGoodAnswers: [Int : [String]]!

并在viewDidLoad()方法中:

self.collectionOfGoodAnswers = [0:  ["Hello", "World"],
                                        1:  ["Welcome", "Friend"]]

然后实施点击操作:

@IBAction func btnClick(sender: AnyObject) {
    for(index, _) in collectionOfGoodAnswers.enumerate() {
        guard let goodAnswer = collectionOfGoodAnswers[index] else { return }
        guard let answer = textFields[index] else { return }
        guard let text = answer.text else { return }

        if goodAnswer.contains(text) {
            textFields[index]?.backgroundColor = UIColor.greenColor()
        }
        else {
            textFields[index]?.backgroundColor = UIColor.redColor()

        }
    }
}
希望它有所帮助。