简体   繁体   English

如何在Swift中将样式应用于所有文本字段

[英]How to apply styles to all text fields in Swift

I'm trying to find the most efficient way to apply these border styles to all text fields in my view controller. 我试图找到将这些边框样式应用于视图控制器中所有文本字段的最有效方法。 It seems crazy to apply this style to all text fields separately. 将此样式分别应用于所有文本字段似乎很疯狂。 Is there an easy way to reference all text fields, or should I create some sort of a style class? 有没有一种简单的方法可以引用所有文本字段,还是应该创建某种样式类?

    textField.layer.cornerRadius = 8.0
    textField.layer.borderColor = (UIColor .grayColor()).CGColor;
    textField.layer.borderWidth = 1.0

Thanks for your help! 谢谢你的帮助!

As Tron5000 say you can use extension like that: 就像Tron5000所说的那样,您可以使用扩展名:

extension UITextField {
    func setPreferences() {
        self.layer.cornerRadius = 8
        self.layer.borderColor = UIColor.grayColor().CGColor
        self.layer.borderWidth = 2
        // etc.
    }
}

And then you can collect all your textfields to one array and iterate over them: 然后,您可以将所有文本字段收集到一个数组中并对其进行迭代:

var myTextFields = [UITextField]()

func setColorsAndBorders() {
    myTextFields = [tf1, tf2, tf3, tf4] // etc

    for item in myTextFields {
        item.setPreferences()
    }
}

I think you'll need to subclass or write an extension for UITextField. 我认为您需要继承或编写UITextField的扩展。 See this page: 看到这个页面:

How may i customise all UITextField appearances for borderWidth? 我如何为borderWidth自定义所有UITextField外观?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM