iOS 如果触摸到特定视图的顶部,则知道 touchesEnded 何时结束

iOS know when touchesEnded if touches on top of certain view

我必须做一些 "snap to grid" 行为,

我有一个拖动图像 "sprite",但我需要 "snap" 如果触摸发生在某个按钮的顶部,我需要将此 sprite 拖到该按钮上,

所以我怎么知道 touchesEnded 是否在某个按钮的顶部, 这是我的代码,但我不知道什么时候触摸结束于 butotn

 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{    
    UITouch *touched = [[event allTouches] anyObject];
    CGPoint location = [touched locationInView:touched.view];

    CGRect recta = touched.view.frame;

    if (CGRectIntersectsRect(recta, self.button_1.frame)) {
        DLog(@"intersected");
    }

}

所以这不会发生, 可以吗?

还是必须自己对照按钮框的XY位置检查画龙点睛的XY位置?

干杯

您可以使用 CGRectIntersectsRect,returns 可以,如果您传递给它的两个矩形相交。

touched.view 是触摸开始的视图。你想知道触摸结束的位置是否在特定按钮的顶部。您可以通过检查触摸相对于按钮的位置是否在按钮的范围内来执行此操作。

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touched = [[event allTouches] anyObject];
    CGPoint locationRelative = [touched locationInView:self.button_1];

    if (CGRectContainsPoint(self.button_1.bounds, locationRelative)) {
        DLog(@"on top of button_1");
    }
}