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?

orkenstein
  • 2,810
  • 3
  • 24
  • 45

3 Answers3

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.

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
  • Will `@IBInspectable var testFonts: UIFont` appear in Interface Builder? – orkenstein Aug 13 '15 at 17:42
  • @orkenstein No :( It's not displayed. but the font size is changed. – Ashish Kakkad Aug 13 '15 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 '15 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 '15 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 '17 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()
}
Zell B.
  • 10,266
  • 3
  • 40
  • 49
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.

marcelosalloum
  • 3,481
  • 4
  • 39
  • 63