我有多个UITextFields,我对边框,半径和颜色进行了相同的更改。
@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
为每个文本字段重复代码五次是非常低效的。我认为for循环将是最好的解决方案,但我无法弄清楚如何替换文本字段名称中的int。例如,
for var i = 0; i < 6; i++ {
self.answer1Text.layer.cornerRadius = 5 // Not sure how to replace the 1 here
}
如果for循环是最好的解决方案,你怎么做?如果没有,最好的实施方式是什么?
谢谢!
答案 0 :(得分:1)
您需要将所有answerTexts存储到NSArray
并循环遍历此数组。在循环迭代中,您可以通过索引从数组到达UITextField
对象并设置属性:
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
}