Mats
Mats

Reputation: 359

Custom object class in Swift

In my app I need to have a lot of labels with similar properties. Let's say they all have to be green. I don't want to have to say lbl.color = UIColor.greenColor()every time. How can I make a custom object class/struct allowing me to say something like var myLbl = CustomLbl() (CustomLblbeing my class).

I'm not sure if this is how you're supposed do it. If not, i have no problem with doing it in some other way.
Also, in my app I would have more properties but i only chose this as an example.

Thanks!

Upvotes: 1

Views: 2021

Answers (2)

Antonio
Antonio

Reputation: 72760

Without having to subclass, you can just add a method to configure your label as you wish:

func customize() {
    self.textColor = UIColor.greenColor()
    // ...
}

and a static function which creates a UILabel instance, customizes and returns it:

static func createCustomLabel() -> UILabel {
    let label = UILabel()
    label.customize()
    return label
}

Put them in a UILabel extension and you're done - you can create a customized label with:

let customizedLabel = UILabel.createCustomLabel()

or apply the customization to an existing label:

let label = UILabel()
label.customize()

Update: for clarity, the 2 methods must be put inside an extension:

extension UILabel {
    func customize() {
        self.textColor = UIColor.greenColor()
        // ...
    }

    static func createCustomLabel() -> UILabel {
        let label = UILabel()
        label.customize()
        return label
    }
}

Upvotes: 1

enes
enes

Reputation: 329

You should use base classes to create your own labels, buttons etc.

class YourLabel: UILabel {

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

        //you can set your properties    
        //e.g
        self.color = UIColor.colorGreen()
}

Upvotes: 1

Related Questions