Is it possible to make @IBDesignable override the values ​​of Interface Builder?

For example, I want to subclass UIButtonand set it to default 20.0f. 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 the preview in Interface Builder , all custom buttons are displayed with the 15.0fdefault font size . Any thoughts?

+6
source share
3 answers

I created a new one IBInspectablelike 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 this helps you :)

This works for me.

+4
source

, init ,

override init(frame: CGRect) {

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

EASY: the following solution usually works or to me

import UIKit

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

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

I hope what you are looking for.

0
source

All Articles