Kashif
Kashif

Reputation: 4632

IBDesignable UIButton IB Render without IBInspectables

I have below code to create a custom IBDesignable UIButton. Note that I do not have any IBInspectables since I do not need any. I want all my custom buttons to be same.

import UIKit

@IBDesignable class ShButton: UIButton {

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

override init(frame: CGRect) {
    super.init(frame: frame)
    self._setup()
}


override func awakeFromNib() {
    self._setup()
}

override func prepareForInterfaceBuilder() {
    self._setup()
}

private func _setup(){
    self.layer.cornerRadius = 5.0
    self.layer.masksToBounds = true
    self.layer.borderColor = UIColor.whiteColor().CGColor
    self.layer.borderWidth = 1.0
    self.setNeedsDisplay()
}

override func drawRect(rect: CGRect) {
    super.drawRect(rect)
}

deinit {
}

}

There are two problems:

  1. ShButton Class does not show in Custom Class dropdown in IB, I have to manually type it and also provide Module name. I also noticed that there is no "Designables Up to Date" indicator showing here either, which shows in many tutorials on the subject.
  2. It does not render in IB. However when I run the project in Simulator, it renders correctly. Am I missing anything to make it render in IB?

Upvotes: 1

Views: 829

Answers (1)

allthethings
allthethings

Reputation: 773

I'm still kind of an iOS newb, but I had a similar situation, and this worked fine for me:

@IBDesignable class ShButton: UIButton {

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

    override init(frame: CGRect) {
        super.init(frame: frame)
        self._setup()
    }

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

    private func _setup(){
        self.layer.cornerRadius = 5.0
        self.layer.masksToBounds = true
        self.layer.borderColor = UIColor.whiteColor().CGColor
        self.layer.borderWidth = 1.0
        self.setNeedsDisplay()
    }
}

This allowed me to set a default cornerRadius on a button without having to use an IBInspectable, and worked in both the storyboard and at runtime.

EDIT: Updated answer

Upvotes: 1

Related Questions