Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

I'd use delegation:

TouchDelegate.h:

#import <UIKit/UIKit.h>

@protocol TouchDelegate <NSObject>
@optional

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

@end

And then in your view (that actually receives the touch event), create a touchDelegate property (or just delegate if there is unlikely to be others):

#import "TouchDelegate.h"

@interface MyView : UIView
@property (weak, nonatomic) id<TouchDelegate> touchDelegate;
...
@end

and then delegate as normal:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if ([_touchDelegate respondsToSelector:@selector(touchesBegan:withEvent:)]) {
        [_touchDelegate touchesBegain:touches withEvent:event];
    }
}

// etc.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top