拖动时在UIButton上填充背景颜色

时间:2016-06-30 01:00:06

标签: ios objective-c uibutton uipangesturerecognizer

我有一个蓝色背景的自定义UIButton。 当我将手指拖过UIButton时,我需要填充红色背景颜色。当我向后拖动手指时,红色应该消失。

我尝试在UIPanGestureRecognizer州使用UIGestureRecognizerStateEnded进行实施。如果不在UIButton之上添加其他视图,我就无法在按钮背景中获得红色。

还有其他方法可以实现吗?

2 个答案:

答案 0 :(得分:0)

添加目标:

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

在控件事件处理程序中重新定位红色叠加视图:

- (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];
    }
}

答案 1 :(得分:0)

使用Sent Event properties的{​​{1}}更改拖动时间颜色使用UIButton,并使用相同的颜色TouchDragEnter

可能对你有帮助吗?