当我们自定义了一个UIButton时,如果采用重绘的方式,将drawRect事件重写了,原有自带的点击的效果就没有了,这时,我们也要自己来重新写的。
例如下面效果的按钮
- (id) initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self addObserver:self forKeyPath:@"highlighted" options:0 context:nil]; //增加对highlighted属性的观察
}
return self;
}
-(void)dealloc
{
[self removeObserver:self forKeyPath:@"highlighted"];//移除对highlighted属性的观察
[super dealloc];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"highlighted"]) {
[self setNeedsDisplay];//当按钮被按下时,重绘按钮
}
}