xcode - swift Detect the correct textfield to add an attribute -
i´m writing input text quiz app, , have array of int can store if answer correct or not 0 or 1 , have 3 textfields write answers, , want change textfields ground color red or green depending on answers variable ,, if index variable 1 change color green , if 0 change color red.. have
@iboutlet var textfield1: uitextfield! @iboutlet var textfield2: uitextfield! @iboutlet var textfield3: uitextfield! //change int 1 if answer correct (3, ea each textfield) var answers = [0,0,0] @ibaction func button(sender: anyobject) { (index, answer) in goodanswers.enumerate() { print (answer) if answer != 0 { print ("ok") } else { print("not ok") } } }
thanks !
you need this:
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() } } }
update:
if want have answers change code this:
declare new property:
var collectionofgoodanswers: [int : [string]]!
and in viewdidload() method:
self.collectionofgoodanswers = [0: ["hello", "world"], 1: ["welcome", "friend"]]
and implement click action:
@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() } } }
hope helps.
Comments
Post a Comment