Is it possible to make @IBDesignable override Interface Builder values?
Asked Answered
R

3

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?

Rubstone answered 13/8, 2015 at 12:39 Comment(0)
M
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.

Mailer answered 13/8, 2015 at 13:34 Comment(5)
Will @IBInspectable var testFonts: UIFont appear in Interface Builder?Rubstone
@Rubstone No :( It's not displayed. but the font size is changed.Mailer
Remove it from listing and paste titleLabel?.font = UIFont.systemFontOfSize(20) from original question. It might confuse some wanderer. And thanks for the clue!Rubstone
Yes it's ok, The only thing i can dream about now - make this default value replace Font value in interface builder.Rubstone
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.Hankins
C
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()
}
Countermeasure answered 13/8, 2015 at 13:17 Comment(0)
O
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.

Offcenter answered 6/2, 2019 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.