Skip to content

Instantly share code, notes, and snippets.

@feighter09
Created April 28, 2016 04:34
Show Gist options
  • Save feighter09/c502d7550e4cdb82d526157f5cf8bef1 to your computer and use it in GitHub Desktop.
Save feighter09/c502d7550e4cdb82d526157f5cf8bef1 to your computer and use it in GitHub Desktop.
IBInspectable UIView Extensions for Fun and Profit
extension UIView {
@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 }
}
@IBInspectable var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set { layer.cornerRadius = newValue }
}
// Proof of concept, not tested
@IBInspectable var backgroundImage: UIImage! {
get { return nil } // maybe use associated objects, you can't add properties in extensions
set {
let imageView = UIImageView(image: newValue)
imageView.frame = bounds
addSubview(imageView)
}
}
}
@EMart86
Copy link

EMart86 commented May 27, 2018

In Swift 4:

extension UIView {
    @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 }
    }
    
    @IBInspectable var cornerRadius: CGFloat {
        get { return layer.cornerRadius }
        set { layer.cornerRadius = newValue }
    }
    
    // Proof of concept, not tested
    @IBInspectable var backgroundImage: UIImage! {
        get { return nil }  // maybe use associated objects, you can't add properties in extensions
        set {
            let imageView = UIImageView(image: newValue)
            imageView.frame = bounds
            addSubview(imageView)
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment