I am still improving my programing skills in iOS(Swift). Today I am thinking about creating a UIView subclasses in a good way. I want to create custom view which is:
- @IBDesignable - I want to see a render of my view in storyboard/xib;
- Creatable from code
I know such methods as init(withFrame)
init()
init(withDecoder)
prepareForInterfacebuilder()
, etc but I don't know how to use them to minimize redundancy of code.
For example here is my custom UIButton
:
import UIKit
@IBDesignable
class SecurityButton: UIButton {
@IBInspectable
var color: UIColor = UIColor.black {
didSet {
setTitleColor(color, for: .normal)
contentEdgeInsets = UIEdgeInsetsMake(0.0, 8.0, 0.0, 8.0)
layer.borderWidth = 1.0
layer.borderColor = color.cgColor
layer.cornerRadius = 6.0
}
}
}
It works good but I know that contentEdgeInsets = UIEdgeInsetsMake(0.0, 8.0, 0.0, 8.0)
layer.cornerRadius = 6.0
layer.borderWidth = 1.0
are called every I set a new color. Where should I place this custom setup to keep my requirements about custom view?
Edit
I do not looking for fix my example. I looking for a good place to initialize my custom view. Suppose that you need to do some time-consuming operations but only ones on create view.