Search code examples
iosobjective-cswiftuibuttonstoryboard

Set a border for UIButton in Storyboard


I can't get a border onto my buttons in Xcode 5 without setting them directly in the code. Is it possible that there's no way to do this on the storyboard without making a custom background image?


Solution

  • You can use key path.

    For example the corner radius (layer.cornerRadius) as describe on the image. You will not be able to see the effects on storyboard, cause this parameters are evaluated at runtime. Now you can use a swift category in UIView (code bellow the picture) in with @IBInspectable to show the result at the storyboard (If you are using the category, use only cornerRadius and not layer.cornerRadius as a key path.

    enter image description here


    extension UIView {
        @IBInspectable var cornerRadius: CGFloat {
            get {
                return layer.cornerRadius
            }
            set {
                layer.cornerRadius = newValue
                layer.masksToBounds = newValue > 0
            }
        }
    }
    

    Here is category from Peter DeWeese answer that allow use keypath layer.borderUIColor to set the border color.

    CALayer+XibConfiguration.h:

    #import <QuartzCore/QuartzCore.h>
    #import <UIKit/UIKit.h>
    
    @interface CALayer(XibConfiguration)
    
    // This assigns a CGColor to borderColor.
    @property(nonatomic, assign) UIColor* borderUIColor;
    
    @end
    

    CALayer+XibConfiguration.m:

    #import "CALayer+XibConfiguration.h"
    
    @implementation CALayer(XibConfiguration)
    
    -(void)setBorderUIColor:(UIColor*)color
    {
        self.borderColor = color.CGColor;
    }
    
    -(UIColor*)borderUIColor
    {
        return [UIColor colorWithCGColor:self.borderColor];
    }
    
    @end