Search code examples
swiftaspects

How to define all aspects of a new UIvariable in creation?


Im creaing a Program in swift where I have a "Test.swift" with a class containing some static variable. One of these variables is a UITextField created like this :

static var textField1 : UITexField = UITextField()

The next thing I would now like to do is give this textField1 some aspects such as font and background colore such as this

static var textField1 : UITexField = UITextField()

Test.textField1.tintColor = UIColor.yellow()

It wount let me do this though because im nof in a function im still in the bare class, now I had the idea of creating a static function which than adds all the aspect and returns the finished Text Field, but I would rather do it somewhat like this :

static var textField1 : UITexField = UITextField(tintColor = UIColor.brown(), Font = etc.)

is this somehow achievable ?


Solution

  • Why not use extensions?

    extension UITextField {
        static func textFieldWithFont(font : UIFont, tintColor : UIColor) -> UITextField {
            let textField = UITextField()
            textField.tintColor = tintColor
            textField.font = font
            return textField
        }
    }
    

    You can use it like so:

    let textField = UITextField.textFieldWithFont(UIFont.systemFontOfSize(17), tintColor: UIColor.yellowColor())