Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView's border color in Interface builder doesn't work?

I am trying to set up a view's layer properties via IB. Everything works except for color of the border (property layer.borderColor):

enter image description here

I remember running into this problem a year ago and I ended up doing it programatically. And still, I can do this programmatically, but I am curious why the layer.borderColorproperty never works via interface builder. I don't want to import QuartzCore, and then write extra line of code just because of this, seems like an overkill.

like image 947
0xSina Avatar asked Feb 09 '13 22:02

0xSina


2 Answers

It's possible to do this, but it's not a built-in feature. This is because the Color type in the User Defined Runtime Attributes panel creates a UIColor, but layer.borderColor holds a CGColorRef type. Unfortunately, there's no way to assign a CGColorRef type in Interface Builder.

However, this is possible through a proxy property. See Peter DeWeese's answer to a different question for a possible solution to this problem. His answer defines a category that allows a proxy color to be set through Interface Builder.

like image 176
mopsled Avatar answered Sep 28 '22 08:09

mopsled


You have to create Category for CALayer:

CALayer+UIColor.h

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

CALayer+UIColor.m

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

And then in User Defined Runtime attributes You can use it as it is on image below:

enter image description here

For Swift it is much more simple:

import QuartzCore  extension CALayer {     @IBInspectable var borderUIColor: UIColor? {         get {             guard let borderColor = borderColor else { return nil }             return UIColor(cgColor: borderColor)         }                  set {             borderColor = newValue?.cgColor         }     } } 

Then in Xcode you can use it like this:

enter image description here

Once you choose sth it is automatically added to your runtime attributes:

like image 32
Bartłomiej Semańczyk Avatar answered Sep 28 '22 08:09

Bartłomiej Semańczyk