6

For example, I want to subclass UIButton and set it's font to 20.0f by default. I can write something like this:

@IBDesignable

class HCButton: UIButton {
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.customInit()
  }

  func customInit () {
    titleLabel?.font = UIFont.systemFontOfSize(20)
  }
} 

But this does not affect preview in Interface Builder, all custom buttons appear with 15.0f font size by default. Any thoughts?

3 Answers 3

4

I have created new IBInspectable as testFonts :

import UIKit

@IBDesignable

class CustomButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.customInit()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.customInit()
    }

    func customInit () {
        titleLabel?.font = UIFont.systemFontOfSize(20)
    }

    convenience init() {
        self.init(frame:CGRectZero)
        self.customInit()
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        self.customInit()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        self.customInit()
    }
}

Hope it helps you :)

This is working for me.

5
  • Will @IBInspectable var testFonts: UIFont appear in Interface Builder?
    – orkenstein
    Aug 13, 2015 at 17:42
  • @orkenstein No :( It's not displayed. but the font size is changed. Aug 13, 2015 at 17:43
  • Remove it from listing and paste titleLabel?.font = UIFont.systemFontOfSize(20) from original question. It might confuse some wanderer. And thanks for the clue!
    – orkenstein
    Aug 13, 2015 at 17:45
  • 1
    Yes it's ok, The only thing i can dream about now - make this default value replace Font value in interface builder.
    – orkenstein
    Aug 13, 2015 at 18:02
  • Hey, @AshishKakkad, great post! But I notice that awakeFromNib function is not needed in my testing to make the customInit setting visible in the interface builder. Is there a reason why you are adding that? Also, I believe convenience init() is not needed either.
    – Yuchen
    Apr 24, 2017 at 14:26
0

I think you must override the init with frame initializer as well to affect that

override init(frame: CGRect) {

    super.init(frame: frame)
    self.customInit()
}
0
0

EASIER: The following solution usually works or me

import UIKit

@IBDesignable
class CustomButton: UIButton {
    open override func layoutSubviews() {
        super.layoutSubviews()
        customInit()
    }

    func customInit () {
        titleLabel?.font = UIFont.systemFontOfSize(20)
    }
}

I hope that's what you're looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.