我需要使用触摸事件,但我试图从另一个类中检测到它,所以如果触摸或移动等我将回到我的主类。 我在" classTouchEvents"中调用init方法。首先来自我的主要课程
objectTouchEvents=[[classTouchEvents alloc]initWith:self.view];
这是" classTouchEvents"
的initWith方法 - (id)initWith:(UIView *)selfView
{
self = [super init];
if (self) {
NSLog(@"here");
view=[[UIView alloc]init];
view=selfView;
// Custom initialization
}
return self;
}
我得到"在这里"记录所以我猜它有效,但我无法检测视图是否触摸或任何东西。这是我在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");
}
但我无法获得有关触摸的任何日志。我需要一些帮助。 提前谢谢。
答案 0 :(得分:8)
我会使用委托:
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
然后在您的视图中(实际上会收到触摸事件),创建一个touchDelegate
属性(如果不可能有其他属性,则创建delegate
):
#import "TouchDelegate.h"
@interface MyView : UIView
@property (weak, nonatomic) id<TouchDelegate> touchDelegate;
...
@end
然后照常委托:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([_touchDelegate respondsToSelector:@selector(touchesBegan:withEvent:)]) {
[_touchDelegate touchesBegain:touches withEvent:event];
}
}
// etc.
答案 1 :(得分:5)
我将使用委托实现UIView的自定义子类。
@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;
在ClassTouchEvents中实现这些委托方法。
在自定义视图中实施触摸事件方法并调用委托。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (self.delegate && [self.delegate respondsToSelector:@selector(touchesBegan:withEventinView)]) {
[self.delegate touchesBegan:touches withEvent:event inView:self];
}
}