自定义手势识别器无法正常工作

Custom Gesture Recognizer doesn't work properly

"touchedBegan" 和 "touchedEnded" 方法都被调用,但我的视图仅在 touchesBegan 方法上改变了背景,而在 touchesEnded 上没有改变。这是我的代码:

@implementation ClickableViewGestureRecognizer

NSString* const COLOR_UNTOUCHED = @"#00000000";
NSString* const COLOR_TOUCHED = @"#33000000";

- (instancetype)init {
    self = [super init];
    return self;
}

- (instancetype)initWithTarget:(id)target
                    action:(SEL)action {
    self = [super initWithTarget:target action:action];
    return self;
}

- (void)touchesBegan:(NSSet *)touches
       withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    super.view.layer.backgroundColor = [self getTouchedColor];
}

- (void)touchesEnded:(NSSet *)touches
       withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    super.view.layer.backgroundColor = [self getUntouchedColor];
}

- (CGColorRef) getUntouchedColor {
    return [JABColor colorFromHexString:COLOR_UNTOUCHED].CGColor;
}

- (CGColorRef) getTouchedColor {
    return [JABColor colorFromHexString:COLOR_TOUCHED].CGColor;
}

@end

这里是 colorFromHexString: 给任何想看的人。

+ (UIColor *)colorFromHexString:(NSString *)hexString {
    unsigned rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    [scanner setScanLocation:1]; // bypass '#' character
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}

你有touchesCancelled方法吗?也许您的 Touch 事件被取消而不是 "ended" ,也尝试覆盖 touchesCancelled

- (void)touchesCancelled:(NSSet *)touches
               withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
    super.view.layer.backgroundColor = [self getUntouchedColor];
}

您是否可以出于测试原因尝试将 [UIColor blackColor] 设置为未更改的颜色?直接,不从 hex

转换

答案是 "colorFromHexString" 给我带来了问题。我把它扔掉了,只使用了 UIColor 方法。