如何观察 UIControl 的 touchInside 属性?
Posted
技术标签:
【中文标题】如何观察 UIControl 的 touchInside 属性?【英文标题】:How to observe the touchInside properties of UIControl? 【发布时间】:2015-06-02 07:51:50 【问题描述】:我需要观察 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;
【问题讨论】:
This 可能会帮助你 我想知道为什么不能观察到touchInside属性? 【参考方案1】:你需要添加一个目标动作
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
并在那里处理您的代码。
然后在该方法中进一步发送操作:
[self sendActionsForControlEvents:UIControlEventValueChanged];
【讨论】:
以上是关于如何观察 UIControl 的 touchInside 属性?的主要内容,如果未能解决你的问题,请参考以下文章