如何知道用户在屏幕上触摸的视图

时间:2013-10-22 09:18:44

标签: ios uiscrollview touch

如果在uiscrollview上有uiscrollview和多个子视图。如何知道用户触摸的位置,即特定视图或滚动视图(空白区域)

2 个答案:

答案 0 :(得分:5)

使用这种方法:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        NSLog(@"View touched: %@", touch.view);
}

每次手指触摸屏幕时都会调用此方法,并且触摸会知道它触摸了哪个视图。

编辑:它不能在UIScrollView上工作,因为滚动视图会自动触摸,请检查:

touchesBegan method not called when scrolling in UIScrollView

How to enable touch began in UIScrollView?

答案 1 :(得分:3)

您有两种方法可以在scrollView中使用- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;检测触摸:

首先,在viewController中实现此方法,并在此viewController上添加scrollview。

第二,我建议:创建一个从UIScrollView继承的自定义类,如下所示: .H:

@interface CustomScrollView : UIScrollView 

@end

的.m:

#import "CustomScrollView.h"


@implementation CustomScrollView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.nextResponder touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    if(!self.dragging){
        [self.nextResponder touchesMoved:touches withEvent:event];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.nextResponder touchesEnded:touches withEvent:event];
}

@end

在你的vc make:

...

CustomScrollView* customScrollView = [[CustomScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];

...

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        NSLog(@"View touched: %@", touch.view);
}