2010-08-30 42 views
3

如何捕获触摸事件,如- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event而没有子类化UIView或使用UIViewControllers。如何设置UIView触摸处理程序而不需要子类化

会发生什么是我有一个简单的UIView编程创建,我需要检测基本的轻敲事件。

+2

你为什么不想要继承它... UIView的子类是理想相同作为UIView ... – 2010-08-30 05:03:12

+0

你可以说我很懒......但子类将有更多的代码/类/文件。我只想捕捉触动,并希望有一个我可以分配给UIView的委托。 – samwize 2010-08-30 05:38:33

+0

hmm ..同样的问题在这里,我不想为了接收触摸事件而继承子类。 – rraallvv 2014-01-01 03:18:59

回答

4

如果您正在为iOS 4编写应用程序,请使用UIGestureRecognizer。然后你可以做你想做的。无需继承即可识别手势。

否则,子类化是要走的路。

+0

这是一个解决方案。我可以使用UIView'addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer'。 – samwize 2010-08-30 05:58:58

+0

注意事项 - 在3.2中添加了,所以你也可以在iPad上使用它们。 – 2010-08-30 06:26:57

1

没有理由不这样做。如果你继承和不添加任何东西,它只是一个UIView由另一个名字调用。你所做的只是拦截你感兴趣的功能。如果你不希望阻止响应者从链接中获取这些事件,不要忘记你可以在你的子类'touchesBegan中执行[super touchesBegan:touches]

+0

这是一个很好的建议,但不是如上所述回答问题。 – hotpaw2 2010-08-30 05:31:28

+0

看起来他知道答案 - touchesBegan等 – 2010-08-30 05:35:23

1

我不明白为什么你不想使用继承UIView的普通方法来捕获触摸事件,但是如果你确实需要做一些奇怪的事情或偷偷摸摸的事情,你可以捕获所有的事件(包括触摸事件)然后通过捕获/处理UIWindow级别的sendEvent:方法将它们发送到视图层次结构中。

+0

这是有用的提示,但不是我想要的。 – samwize 2010-08-30 05:36:27

+0

如果有附加事件处理程序的方法,那么有人不想要继承UIView是非常合乎逻辑的。这是一个更强大的设计模式。但如果没有办法做到这一点,就没有办法做到这一点。 (尽管看起来UIGestureRecognizer可能是最好的选择。) – 2011-01-14 03:40:13

1

CustomGestureRecognizer.h

#import <UIKit/UIKit.h> 

@interface CustomGestureRecognizer : UIGestureRecognizer 
{ 
} 

- (id)initWithTarget:(id)target; 

@end 

CustomGestureRecognizer.mm

#import "CustomGestureRecognizer.h" 
#import <UIKit/UIGestureRecognizerSubclass.h> 

@interface CustomGestureRecognizer() 
{ 
} 
@property (nonatomic, assign) id target; 
@end 

@implementation CustomGestureRecognizer 

- (id)initWithTarget:(id)target 
{ 
    if (self = [super initWithTarget:target action:Nil]) { 
     self.target = target; 
    } 
    return self; 
} 

- (void)reset 
{ 
    [super reset]; 
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesBegan:touches withEvent:event]; 

    [self.target touchesBegan:touches withEvent:event]; 
} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesMoved:touches withEvent:event]; 

    [self.target touchesMoved:touches withEvent:event]; 
} 

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesEnded:touches withEvent: event]; 

    [self.target touchesEnded:touches withEvent:event]; 
} 
@end 

用法:

CustomGestureRecognizer *customGestureRecognizer = [[CustomGestureRecognizer alloc] initWithTarget:self]; 
[glView addGestureRecognizer:customGestureRecognizer];