Search code examples
swiftgenericsxcode-storyboardibinspectable

Use @IBInspectable with any UIView subclass within storyboards


I have a class to use with @IBInspectable, to get the properties within my storyboard. Here is a small chunk of it:

/// UIView subclass to allow creating corners, shadows, and borders in storyboards.
final class GEView: UIView {

    // MARK: - Rounded corners
    @IBInspectable
    var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = self.cornerRadius
            layer.masksToBounds = true
        }
    }

    /* ... */
}

This works completely fine within UIViews in my storyboard. However, I want this to also work with UIImageViews and other subclasses of UIView. Is this possible without subclassing my GEView, by somehow making this a generic?


Solution

  • Move your code to UIView's @IBDesignable extension like below:

    @IBDesignable extension UIView {    
        @IBInspectable var cornerRadius: CGFloat {
            set {
                layer.cornerRadius = newValue
                layer.masksToBounds = true
            }
            get {
                return self.cornerRadius
            }
        }
    }
    

    Clear unwanted values/types of previously deifned vars in your GEView. Here are values in inspector.

    enter image description here

    Properties available in inspector of any UIView, included itself.

    Properties avaliable in storyboard interface