Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton User Defined Run Time Attributes Does not Work

I am trying to draw a border around a custom UIButton. This doesn't work: enter image description here

why?

like image 799
Michal Shatz Avatar asked Oct 14 '25 10:10

Michal Shatz


2 Answers

click here to solve the problem

Please allow me to repeat it here..^_^

The runtime attribute feature allows us to set a UIColor type, which we need to translate to a CGColor type. To accomplish this, we need to extend the CALayer class with a property that will translate the UIColor to the CGColor we need for the border and shadow.

You can extend classes in Objective-C using a category. I added two properties called borderIBColor and shadowIBColor that are of type UIColor. The IB stands for interface builder. I have to give these properties a unique name to avoid name conflicts with the original properties called borderColor and shadowColor that are of the type CGColor.

Please see the following code.

CALayer+RuntimeAttribute.h

@import QuartzCore;

@interface CALayer (IBConfiguration)

@property(nonatomic, assign) UIColor *borderIBColor;

@end

CALayer+RuntimeAttribute.m

@implementation CALayer (IBConfiguration)

- (void)setBorderIBColor:(UIColor *)color {
    self.borderColor = color.CGColor;
}

- (UIColor *)borderIBColor {
    return [UIColor colorWithCGColor:self.borderColor];
}

@end

Finally, when you set the borderColor of runtime attribute feature in xib or storyboard, please set borderIBColor instead of borderColor. It looks like layer.borderIDColor

Have your fun.

like image 65
tianglin Avatar answered Oct 17 '25 04:10

tianglin


cornerRadius & cornerRadius is CGFloat, use Number to change.

borderColor is CGColor, can't be change by Runtime Attribute. (you can add a category to support UIColor to change CGColor)

Helper Category:

UIView+IBHelper.h:

@interface UIView (IBHelper)

- (void)setBorderColor:(UIColor *)color;

@end

UIView+IBHelper.m:

@implementation UIView (IBHelper)

- (void)setBorderColor:(UIColor *)color
{
    self.layer.borderColor = color.CGColor;
}

@end

and use borderColor in Runtime Attribute. directly

enter image description here

like image 39
Mornirch Avatar answered Oct 17 '25 04:10

Mornirch