iOS - Detecting touches in a UIView?

前端 未结 4 534
无人共我
无人共我 2021-01-12 01:55

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

相关标签:
4条回答
  • 2021-01-12 02:13

    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
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-12 02:17

    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;
            }
    }
    
    0 讨论(0)
  • 2021-01-12 02:19

    One way to do it (though there might be others) is to disable user interaction for the subviews and make their parent view track the movement (use the hitTest method to figure out which view the touch is currently over).

    0 讨论(0)
  • 2021-01-12 02:30

    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))
            {
    
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题