1

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!

Mats
  • 359
  • 2
  • 6
  • 13

2 Answers2

1

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()
}
enes
  • 329
  • 1
  • 11
  • I modified the code slightly to get rid of some errors. I had to put `required`before the `init(coder aDecoder: NSCoder!) {` and also the color was supposed to be `greenColor()` (my bad). How do I make a label that will have these properties? – Mats Jul 01 '15 at 12:25
1

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
    }
}
Antonio
  • 71,651
  • 11
  • 148
  • 165
  • I'm getting an error saying `UILabel does not have a member named customize` in the static function at `label.customize()`... @Antonio – Mats Jul 01 '15 at 14:36
  • 1
    Did you put them inside a `extension UILabel { ... }`? – Antonio Jul 01 '15 at 14:37