圆角视图上的UIGestureRecognizer

时间:2015-06-02 12:21:04

标签: ios objective-c uigesturerecognizer rounded-corners uipangesturerecognizer

我有一个UIView,我使用下面的代码来实现它。

[myView setBackgroundColor:[UIColor redColor]];
[[myView layer] setCornerRadius:[myView bounds].size.height / 2.0f];
[[myView layer] setMasksToBounds:YES];
[myView setClipsToBounds:YES];

然后添加UIPanGestureRecognizer以移动框

UIPanGestureRecognizer *panGesture=[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(boxIsMoving:)];
        [myView addGestureRecognizer:panGesture];

但问题是当用户在该轮之外点击但在实际帧中并开始拖动我的视图也开始移动。任何人都可以建议我怎么能忽略这一轮之外的接触。

2 个答案:

答案 0 :(得分:5)

您可以使用此委托方法。如果触摸位于拐角半径之外,它将返回NO。

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    CGPoint  touchPoint = [touch locationInView:myView];
    if (CGRectContainsPoint(myview.bounds, touchPoint))
    {
        CGFloat centerX = CGRectGetMidX(myView.bounds);
        CGFloat centerY = CGRectGetMidY(myView.bounds);
        CGFloat radius2 = pow((touchPoint.x -centerX),2)+ pow((touchPoint.y - centerY), 2);
        if (radius2 < pow(CGRectGetWidth(myView.frame)/2, 2))
        {
            return YES;
        }
    }
    return NO;
}

答案 1 :(得分:0)

正如Erik Dolor建议您可以计算手势与视图中心点之间的距离。使用这样的东西;

- (IBAction)boxIsMoving:(UIPanGestureRecognizer *)gestureRecognizer
{
    CGPoint viewCentre = CGPointMake(myView.bounds.size.width / 2, myView.bounds.size.height / 2);

    CGPoint gesturePosition = [gestureRecognizer locationInView:self.view];

    float distanceGestureToViewCentre = abs((sqrt((viewCentre.x - gesturePosition.x) 
                                             * (viewCentre.x - gesturePosition.x)
                                             + (viewCentre.y - gesturePosition.y) 
                                             * (viewCentre.y - gesturePosition.y))));

    if(distanceTapToViewCentre < radiusOfView)
    {
        // Handle pan
    }
    else
    {
        // Do nothing
    }
}