mjr mjr - 7 months ago 6
Swift Question

How to change properties of multiple UI elements

I'm trying to make a set of

UILabel
s bold, and figured it could be done with something like a CSS class. The only way I thought of though is subclassing
UILabel
and adding it as a Custom Class to each label:

import UIKit

class BoldLabel: UILabel {
override internal var font: UIFont? {
get {
return UIFont.boldSystemFontOfSize(16.0)
}
}
}


But this gives an error "Getter for 'font' with Objective-C selector 'font' conflicts with getter for 'font' from superclass 'UILabel' with the same Objective-C selector". So is there a way to do it like this, or a different way to easily make a bunch of labels' fonts bold?

Answer
import UIKit

class BoldLabel: UILabel {

//This method is call when you affect this class to a UILabel in your STORYBOARD
required init?(coder aDecoder: NSCoder) {
    super.init(coder:aDecoder)
    self.setup()
}

//This method is call when you programatically create an instance of this UILabel class
override init(frame:CGRect) {
    super.init(frame:frame)
    self.setup()
}

func setup() {
    //All custom properties of this label class here
    self.font = UIFont.boldSystemFontOfSize(28)
}
}

Results with UILabels from storyboard :

enter image description here

Comments