代码之家  ›  专栏  ›  技术社区  ›  samwize

如何在没有子类化的情况下设置UIView touch处理程序

  •  3
  • samwize  · 技术社区  · 16 年前

    如何捕捉触摸事件,例如 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 没有子类化UIView,也没有使用UIViewControllers。

    所发生的是,我有一个简单的UIView创建编程,我需要检测基本的点击事件。

    4 回复  |  直到 16 年前
        1
  •  4
  •   bstahlhood    16 年前

    如果您正在为iOS 4编写应用程序,请使用UIGestureRecognizer。你可以做你想做的事。识别手势而不进行子类化。

    否则,子类化就是一种方法。

        2
  •  1
  •   Adam Eberbach Adil Shaikh    16 年前

    没有理由不这样做。如果你子类化什么都不加,那只是一个 UIView [super touchesBegan:touches] 在你的子类里面 touchesBegan

        3
  •  1
  •   hotpaw2    16 年前

        4
  •  1
  •   rraallvv    12 年前

    CustomGestureRecognizer.h

    #import <UIKit/UIKit.h>
    
    @interface CustomGestureRecognizer : UIGestureRecognizer
    {
    }
    
    - (id)initWithTarget:(id)target;
    
    @end
    

    卡斯tomgestureignizer.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];
    
    推荐文章