我需要观察UIControl的touchInside属性,但是因为它不能通过使用KVO来工作。谁能告诉我,如何解决这个问题?
#define SB_NORMAL_BORDER_COLOR [UIColor colorWithWhite:0.751 alpha:1.000].CGColor
#define SB_TOUCH_BORDER_COLOR [UIColor colorWithRed:0.077 green:0.627 blue:1.000 alpha:1.000].CGColor
#define SB_OBSERVER_KEYPATH @"touchInside"
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.layer.borderWidth=1.0f;
self.layer.borderColor=SB_NORMAL_BORDER_COLOR;
self.backgroundColor = [UIColor colorWithRed:0.881 green:0.901 blue:0.810 alpha:1.000];
self.layer.cornerRadius=self.bounds.size.width/2;
[self addObserver:self forKeyPath:SB_OBSERVER_KEYPATH options:NSKeyValueObservingOptionNew context:nil];
}
return self;
}
此类是UIControl子类。
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"Observer");
if(![keyPath isEqualToString:SB_OBSERVER_KEYPATH]) return;
BOOL isTouch=[change[@"new"] boolValue];
if(isTouch){
self.layer.borderColor=SB_TOUCH_BORDER_COLOR;
[self sendActionsForControlEvents:UIControlEventTouchUpInside];
}else{
self.layer.borderColor=SB_NORMAL_BORDER_COLOR;
}
}
答案 0 :(得分:0)
您需要添加目标操作
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
并在那里处理你的代码。
然后用该方法进一步发送动作:
[self sendActionsForControlEvents:UIControlEventValueChanged];