Bob McGinn
Bob McGinn

Reputation: 73

For loop for multiple UITextFields

I have multiple UITextFields and I'm making the same changes to the border, radius and color.

@IBOutlet weak var answer1Text: UITextField!
@IBOutlet weak var answer2Text: UITextField!
@IBOutlet weak var answer3Text: UITextField!
@IBOutlet weak var answer4Text: UITextField!
@IBOutlet weak var answer5Text: UITextField!

self.answer1Text.layer.cornerRadius = 5
self.answer1Text.layer.borderWidth = 2

let borderColor = UIColor(colorLiteralRed: 125.0/255.0, green:210.0/255.0, blue: 238.0/255.0, alpha: 1.0)
self.answer1Text.layer.borderColor = borderColor.CGColor

Repeating the code five times for each textfield is very inefficient. I was thinking a for loop would be the best solution but I can't figure out how to replace the int in the text field name. For example,

for var i = 0; i < 6; i++ {
    self.answer1Text.layer.cornerRadius = 5 // Not sure how to replace the 1 here
}

If a for loop is the best solution, how do you do so? If not, what's the best way to implement?

Thanks!

Upvotes: 0

Views: 59

Answers (1)

Shamsiddin Saidov
Shamsiddin Saidov

Reputation: 2281

You need to store all your answerTexts to NSArray and loop through this array. In iteration of loop you can reach to your UITextField object from an array by index and set your properties:

var answerTextsArray = [self.answer1Text, self.answer2Text, self.answer3Text, self.answer4Text, self.answer5Text]
for var i = 0; i < answerTextsArray!.count; i++ {
    var myTextField = answerTextsArray[i]
    myTextField.layer.cornerRadius = 5
    myTextField.layer.borderWidth = 2
    let borderColor = UIColor(colorLiteralRed: 125.0/255.0, green: 210.0/255.0, blue: 238.0/255.0, alpha: 1.0)
    myTextField.layer.borderColor = borderColor.CGColor
}

Upvotes: 1

Related Questions