iosstoryboardibdesignableibinspectable

Apply IBInspectable to all view types in iOS


I'm trying to apply IBInspectable to all types of view like UIView, UIButton, UITextField, UIImageView, etc.
Here's what I did:

@IBDesignable
class BaseView: UIView
{
    override func layoutSubviews() {
        super.layoutSubviews()

        updateCornerRadius()
    }

    @IBInspectable var rounded: Bool = false {
        didSet {
            updateCornerRadius()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 4 {
        didSet {
            updateCornerRadius()
        }
    }

    private func updateCornerRadius() {
        layer.cornerRadius = rounded ? cornerRadius : 0
    }
}

It is working fine with all UIView using BaseView subclasses in storyboard, but how can I use this for buttons, text fields, image views, etc?

May be using protocols or extensions to avoid repeating this code to all other types of views...


Solution

  • You should use an extension instead of a subclass, and access the layer property directly:

    extension UIView
    {
        @IBInspectable var cornerRadius: CGFloat {
            get {
                return layer.cornerRadius;
            }
            set(value) {
                layer.cornerRadius = value;
            }
        }
    
        var rounded: Bool {
            return layer.cornerRadius > 0.0;
        }
    }
    

    Note: Since you're not implementing drawRect using @IBDesignable is needless. You can't implement roundedas a settable property this way, but you can have a read-only property for that.