【问题标题】:How to observe the touchInside properties of UIControl?如何观察 UIControl 的 touchInside 属性?
【发布时间】: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属性?

标签: ios objective-c key-value-observing uicontrol


【解决方案1】:

你需要添加一个目标动作

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

并在那里处理您的代码。

然后在该方法中进一步发送操作:

[self sendActionsForControlEvents:UIControlEventValueChanged];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多