lgsanjos
lgsanjos

Reputation: 39

How to create a style or theme on swift so I can set color to all UITextField

It seems to be pretty obvious but I couldn't find much about it after hours.

I'm build an App on swift 2.0 and I have a dark background to all views.

I want to set a common background and color to all my text views, people recommend that each view should set the properties on viewDidLoad, but I don't want to set to each textView one by one the same information. It will be a hell to maintain.

Any hints?

Upvotes: 0

Views: 1433

Answers (3)

Duy Pham
Duy Pham

Reputation: 211

One approach is to use UIAppearance with to change all UITextView, or you can subclass UITextView and modify the object after initialisation, then use that subclass instead of UITextView.

Upvotes: 0

hannad
hannad

Reputation: 822

Subclass UITextView and set the properties to what you desire in the init method. Then have each of your UITextView have a Custom Class set to your UITextView subclass.

Example:

class UITextViewSubclass: UITextView {
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        backgroundColor = UIColor.whiteColor()
    }
}

With this approach, you could also declare some @IBInspectable properties which means they can be modified from the Inspector, if you want to change this color from the Inspector instead of changes inside your code.

class UITextViewSubclass: UITextView {
    @IBInspectable var customBackgroundColor: UIColor = UIColor.whiteColor() {
        didSet {
            backgroundColor = customBackgroundColor
        }
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        backgroundColor = customBackgroundColor
    }
}

Upvotes: 2

Swinny89
Swinny89

Reputation: 7373

Technically yes, each one should be done separately so that you have more control over things. However, if you want to change the background color of all of your text fields you can do it like this:

UITextField.appearance().backgroundColor = //Your color

You can also change the caret color using this:

UITextField.appearance().tintColor = //Your color

If you want to change these colors for a UITextView then simply swap UITextField.appearance()... for UITextView.appearance()...

Upvotes: 2

Related Questions