Skip to content

Instantly share code, notes, and snippets.

@niczyja
Created September 1, 2021 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niczyja/01ed21655b24909e68ec0b87d58c5fd3 to your computer and use it in GitHub Desktop.
Save niczyja/01ed21655b24909e68ec0b87d58c5fd3 to your computer and use it in GitHub Desktop.
UIKit extensions with additional @IBInspectable properties
import UIKit
extension UIButton {
@IBInspectable var disabledBackgroundColor: UIColor? {
get {
guard let image = image(for: .disabled) else { return nil }
return UIColor(patternImage: image)
}
set { setBackgroundColor(newValue, for: .disabled) }
}
@IBInspectable var highlightedBackgroundColor: UIColor? {
get {
guard let image = image(for: .highlighted) else { return nil }
return UIColor(patternImage: image)
}
set { setBackgroundColor(newValue, for: .highlighted) }
}
@IBInspectable var selectedBackgroundColor: UIColor? {
get {
guard let image = image(for: .selected) else { return nil }
return UIColor(patternImage: image)
}
set { setBackgroundColor(newValue, for: .selected) }
}
func setBackgroundColor(_ color: UIColor?, for state: UIControl.State) {
guard let color = color else {
setBackgroundImage(nil, for: state)
return
}
let size = CGSize(width: 1.0, height: 1.0)
let image = UIGraphicsImageRenderer(size: size).image { context in
context.cgContext.setFillColor(color.cgColor)
context.fill(CGRect(origin: .zero, size: size))
}
setBackgroundImage(image, for: state)
}
}
import UIKit
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get { layer.cornerRadius }
set { layer.cornerRadius = newValue }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment