Search code examples
iosobjective-ctouchesbegantouchesmovedtouch-event

How to detect touchesBegan, touchesMoved, touchesEnded events from another class


I need to use touch events but i am trying to detect it from another class, so i will call back to my main class if touched or moved etc. I am calling init method in "classTouchEvents" firstly from my main class like that

objectTouchEvents=[[classTouchEvents alloc]initWith:self.view];

here is initWith method of "classTouchEvents"

 - (id)initWith:(UIView *)selfView
{
    self = [super init];
    if (self) {
        NSLog(@"here");
        view=[[UIView alloc]init];
        view=selfView;
        // Custom initialization
    }
    return self;
}

and i get "here" log so i guess it is working but i cant detect if view get touch or anything. Here is my touch events in classTouchEvents

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    NSLog(@"touchBegan");
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
 NSLog(@"touchMoved");
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"touchEnded");
}

But i cant get any log about touches. I need some help. Thanks in advance.


Solution

  • I would implement a custom subclass of UIView with a delegate.

    @protocol TouchEventsDelegate <NSObject>
    
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event inView:(UIView *)view;
    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event inView:(UIView *)view;
    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event inView:(UIView *)view;
    
    @end
    
    @property (weak, nonatomic) id<TouchEventsDelegate> delegate;
    

    Implement these delegate methods in your ClassTouchEvents.

    Implement the touch events method in your custom view and call the delegate.

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        if (self.delegate && [self.delegate respondsToSelector:@selector(touchesBegan:withEventinView)]) {
            [self.delegate touchesBegan:touches withEvent:event inView:self];
        }
    }