iOS – 在UIView中检测触摸?

所以我有一个假设检测触摸的UIView的子类。 仅当触摸在当前视图内开始时,视图检测才会触摸。 当触摸开始于视图之外,并且在我的自定义视图中移动touchesMoved不会被调用。 检测当前视图中尚未启动的移动触摸的任何解决scheme?

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

以下解决scheme工作。 我有多个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)) { } } } 

这应该解决它:

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

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

尝试这个….

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