Reputation: 598
I want to subclass UIView to support gradients (border / fill). I have subclass with @IBInspectable vars, so I'm able to setup this behavior in IB.
I also need to subclass also UIButton with the same methods. Is there any way I can do it without copying all the methods and instance variables to that subclass of UIButton?
Upvotes: 1
Views: 73
Reputation: 6058
Multiple class inheritance is not allowed in Swift (only multiple protocol inheritance), therefore what you are trying to achieve is not straight-forwardly possible.
One of the possible workarounds, however, is to use extension
for UIView
. Provided that both UIView (itself) and UIButton
are variants of UIView
, the following code would apply to them all.
Example with corner radius:
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
}
Now, even non-subclassed UIButton
will acquire this property, which will be reflected in Interface Builder.
You can try employing the power of extensions to implement unified IBInspectables. One obstacle you will inevitably stumble across, however, is that you won't be able to have any storage in the extension. But for several cases this can serve as a solution.
P.S. Few other examples of use (added to UIView
extension):
@IBInspectable var borderColor: UIColor? {
get { return layer.borderColor.map(UIColor.init) }
set { layer.borderColor = newValue?.cgColor }
}
@IBInspectable var borderWidth: CGFloat {
get { return layer.borderWidth }
set { layer.borderWidth = newValue }
}
Upvotes: 1