Skip to content

Instantly share code, notes, and snippets.

@aibobrov
Created September 17, 2018 13:58
Show Gist options
  • Save aibobrov/5ff5cc9c1a10cbc824eeca1cd316e309 to your computer and use it in GitHub Desktop.
Save aibobrov/5ff5cc9c1a10cbc824eeca1cd316e309 to your computer and use it in GitHub Desktop.
IBDesignable subclass of UIButton
import UIKit
@IBDesignable
class Button: UIButton {
// MARK: - Layer stuff
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
// MARK: - IBInspectable border
@IBInspectable
var borderColor: UIColor? {
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
// MARK: - IBInspectable shadow
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable
var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable
var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable
var shadowColor: UIColor? {
get {
guard let color = layer.shadowColor else { return nil }
return UIColor(cgColor: color)
}
set {
layer.shadowColor = newValue?.cgColor
}
}
@IBInspectable
var imageTintColor: UIColor? {
get {
return imageView?.tintColor
}
set {
imageView?.tintColor = newValue
}
}
@IBInspectable
var onHightLightBackgroundColor: UIColor?
override var isHighlighted: Bool {
didSet {
guard onHightLightBackgroundColor != nil else { return }
backgroundColor = isHighlighted ? onHightLightBackgroundColor : .clear
}
}
public func clear() {
layer.cornerRadius = 0
layer.borderColor = nil
layer.borderWidth = 0
layer.shadowRadius = 0
layer.shadowOpacity = 0
layer.shadowOffset = .zero
layer.shadowColor = nil
imageView?.tintColor = .clear
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layer.cornerRadius = cornerRadius
layer.borderColor = borderColor?.cgColor
layer.borderWidth = borderWidth
layer.shadowRadius = shadowRadius
layer.shadowOpacity = shadowOpacity
layer.shadowOffset = shadowOffset
layer.shadowColor = shadowColor?.cgColor
imageView?.tintColor = imageTintColor ?? .clear
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment