0
votes

I have a custom UIButton with a blue background. When I drag my finger over the UIButton, I need a red background color to be filled. When I drag my finger back, the red color should disappear.

I tried an implementation using UIPanGestureRecognizer on UIGestureRecognizerStateEnded state. Without adding another view on top of UIButton, I couldn't get red color in the button background.

Is there another way I can implement this?

2

2 Answers

0
votes

Use the Sent Event properties of the UIButton for the changing the drag time color use TouchDragEnter and for take back the same color use TouchCancel.

may be it helps you?

0
votes

Add targets:

[button addTarget: self 
           action: @selector(buttonTouchStarted:withEvent:) 
 forControlEvents: UIControlEventTouchDragEnter | UIControlEventTouchDown];
[button addTarget: self 
           action: @selector(buttonTouchEnded:withEvent:)
 forControlEvents: UIControlEventTouchDragExit | UIControlEventTouchUpInside | UIControlEventTouchCancel];

And reposition a red overlay view in the control event handlers:

- (void) buttonTouchStarted:(UIButton *)button withEvent:(UIEvent *)event {
    CGPoint location = [[event touchesForView:button].anyObject locationInView:button];

    UIView *redView = [button viewWithTag:42];
    if (! redView) {
        // Install a red overlay
        redView = [[UIView alloc] initWithFrame:CGRectZero];
        redView.backgroundColor = [UIColor redColor];
        redView.alpha = 0.5f;
        redView.tag = 42;

        // IMPORTANT: We don't want this overlay view to block touches
        redView.userInteractionEnabled = NO;

        [button addSubview:redView];
    }

    CGRect frame = button.bounds;
    frame.size.width = location.x;
    redView.frame = frame;
}

- (void) buttonTouchEnded:(UIButton *)button withEvent:(UIEvent *)event {
    UIView *redView = [button viewWithTag:42];
    if (redView) {
        [redView removeFromSuperview];
    }
}