I try to implement my category of UIButton so that the button instance can have predefined attributes like border color, border corner, etc. Here is my code to setup the button in .m file of my category:
-(void)buttonForMe {
[[self layer] setCornerRadius:2];
[[self layer] setBorderColor:self.tintColor.CGColor];
[[self layer] setBorderWidth:1];
}
As you can see on my 2nd line, I set the borderColor to be tintColor so that when a user touch the button, the border also fades like the text. But it didn't work.. I search around Tintcolor in custom border of UIButton and follow the answer and it didn't work either.
-(void)tintColorDidChange {
[super tintColorDidChange];
[self setNeedsDisplay];
NSLog(@"color changed");
}
I found that the above method never called although the tintcolor of my Button's Text did change whenever I pressed. Just don't know why that method never called? Is it because I implement a Category not a Subclass of UIButton? Thanks.
I used KVO to monitor tintColor and got nothing.So, I think The reason why tintColorDidChange not called is that the tintColor not changed when click. If you want your layer fade when click,you may make subclass of UIButton, then to use KVO.
Sample Code:
@implementation CustomButton
-(instancetype)init{
if (self = [super init]) {
[self setUp];
}
return self;
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
[self setUp];
}
return self;
}
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self setUp];
}
return self;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSNumber * newValue = [change objectForKey:NSKeyValueChangeNewKey];
if (newValue.boolValue) {
self.layer.opacity = 0.3;
}else
{
self.layer.opacity = 1.0;
}
}
-(void)setUp{
[[self layer] setCornerRadius:2];
[[self layer] setBorderColor:self.tintColor.CGColor];
[[self layer] setBorderWidth:1];
[self addObserver:self forKeyPath:@"highlighted" options:NSKeyValueObservingOptionNew context:0];
}
-(void)dealloc{
[self removeObserver:self forKeyPath:@"highlighted"];
}
@end
BTY:I do not suggest to override method in category.