简体   繁体   中英

iOS - Detecting touches in a UIView?

So I have a Subclass of UIView that is suppose to detect touches. The view detect touches only if the touches started inside the current view. When the touches start outside of the view and they move inside my custom view touchesMoved doesn't get called. Any solution to detect moving touches that have not started in the current view?

@implementation MycustomView

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

@end

The following solution worked. I have multiple instances of MyCustomView; as the touches move I want to detect the views that are being touched

I ended up moving touch detection from MyCustomView to its superView, so the following code is no longer in MyCustomView class:

- (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))
        {

        }
    }
}

this should fix it:

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

Try this....

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

一种方法(尽管可能有其他方法)是禁用子视图的用户交互并使其父视图跟踪移动(使用hitTest方法确定触摸当前所在的视图)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM