iOS - 在UIView中检测触摸?

9

我有一个UIView的子类,它应该检测触摸。该视图仅在触摸从当前视图内开始时才检测到触摸。当触摸从视图外部开始并移动到我的自定义视图内部时,touchesMoved不会被调用。有没有解决办法来检测未在当前视图内开始的移动触摸?

@implementation MycustomView

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
   // This only gets called if touches have started in the current View
} 

@end

1
这是已记录并预期的行为。也许,如果您能提供一些关于您想要实现什么的见解,有人就可以帮助您了解如何做到这一点。 - NJones
我在屏幕上有多个自定义视图,我想检测当触摸移动到它们上面时的UIView。 - aryaxt
4个回答

20
以下解决方案有效。我有多个MyCustomView实例;随着触摸事件的移动,我想要检测到被触摸的视图。
最终,我将触摸检测从MyCustomView移动到它的superView中,因此以下代码不再在MyCustomView类中:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.contentView];

    for (UIView *view in self.contentView.subviews)
    {
        if ([view isKindOfClass:[MyCustomView class]] &&
            CGRectContainsPoint(view.frame, touchLocation))
        {

        }
    }
}

1

这应该可以解决问题:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [[event allTouches] anyObject];
    for (UIView* subView in self.subviews) 
    {
        if([subView pointInside:[self convertPoint:touch toView:subView] withEvent:event])
        {
            //do your code here
        }
    }
}

它的行为与我已有的相同。我的触摸经过5个不同的UIView,它总是返回触摸开始的第一个视图。 - aryaxt
这段代码与您发布的完全一样,只不过我在其中加入了一个NSlog:NSLog(@"%@", [touch view]); - aryaxt

0
一种方法(虽然可能还有其他方法)是禁用子视图的用户交互,并使它们的父视图跟踪移动(使用hitTest方法来确定触摸当前位于哪个视图上)。

0

试试这个...

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    for(UITouch *touch in touches)
    {
        CGPoint touchPointFirstBtn = [touch locationInView:self.ChordView];
        if(CGRectContainsPoint(_btnC.frame, touchPointFirstBtn))
        {
            if (!_btnC.isHighlighted)
            {
                if(!Boolean)
                {
                    title = @"C";
                    [_tlbView reloadData];
                    NSLog(@"%@",@"touches C");

                }
                [_btnC setHighlighted:YES];
                Boolean = YES;

            }
        }
        else
        {
            [_btnC setHighlighted:NO];
            Boolean = NO;
        }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接