如何使Touch-Up-Inside仅在正确的控制中实际触摸内部触发?

时间:2011-06-29 19:16:37

标签: objective-c cocoa-touch

我有一个3X3 UI按钮的矩阵,我希望允许用户拖动他的手指并根据手指离开触摸面板的位置激发正确的事件。

目前,如果手指触及该按钮,触摸内部将仅触发按钮。

获得理想行为的最简单方法是什么?

2 个答案:

答案 0 :(得分:2)

我想这将取决于你是否希望按钮除了这种修饰行为之外还要做其他事情。我猜你确实想要这个。

最灵活的行为可能来自附加到按钮的超级视图的手势识别器。您只需要几行来设置它,并使用一种方法来解释它,所以如果您以后采用不同的方式,它很容易放入或移除。

UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleDrag:)];

recognizer.cancelsTouchesInView = NO; //So the user can still interact with controls in the modal view
[self.view addGestureRecognizer:recognizer];
[recognizer release];

所以现在我们配置了识别器。我们如何处理它?<​​/ p>

- (void)handleDrag:(UIPanGestureRecognizer *)sender
{
    //We care only about touching *up*, so let's not bother checking until the gesture ends

    if (sender.state == UIGestureRecognizerStateEnded)
    {
        CGPoint location = [sender locationInView:self.view];

        //Iterate through your button collection

        for (UIButton *button in self.buttons)
        {

            //Let's test to see if the point is inside this button
            if (![button pointInside:[button convertPoint:location fromView:self.view] withEvent:nil]) 
            {
                //Do your thing
                [self userTouchedUpOnButtonWithIndex:button.tag] //For example
                //or
                [self userTouchedUpOnButtonWithIndex:[self.buttons indexOfObject:button]];

                break;
            }
        }
}

够简单吗?

答案 1 :(得分:1)

parentView的大小为3x3,其中9个按钮的大小为1x1,每个按钮作为子视图。 parentView是firstResponder。 parentView处理所有触摸事件。 parentView的UIController确定响应哪个按钮。