[英]Detect touch on UIView with Interface Builder
How can I detect touches in a UIviewController
for a UIView
with code only (without Interface Builder)? 如何仅使用代码(没有Interface Builder)在
UIView
的UIviewController
检测触摸?
I found the touchesBegan method but it doesn't get called ever. 我找到了touchesBegan方法,但是它从未被调用过。 I didn't initialize anything else regarding this method.
关于此方法,我没有初始化其他任何事情。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
#import "TouchView.h"
//TouchView.h
#import <Foundation/Foundation.h>
#import "TouchViewDelegate.h"
@interface TouchView : UIView {
id <TouchViewDelegate> delegate;
}
@property (retain) id delegate;
@end
//TouchView.m
@implementation TouchView
@synthesize delegate;
-(id) initWithFrame:(CGRect)frame
{
self.userInteractionEnabled = YES;
return self;
}
-(id) initWithCoder:(NSCoder *)aDecoder
{
self.userInteractionEnabled = YES;
return self;
}
-(void) awakeFromNib
{
self.userInteractionEnabled = YES;
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[delegate touchDown:self];
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[delegate touchUp:self];
}
@end
//TouchViewDelegate.h
#import <UIKit/UIKit.h>
@protocol TouchViewDelegate
-(void) touchDown:(id) sender;
-(void) touchUp:(id)sender;
@end
I would read over the Touch Events sections of the iPhone Application Programming Guide. 我将阅读《 iPhone应用程序编程指南》的“ 触摸事件”部分 。
UIViewController and UIView are both UIResponders , which is responsible for handling the events. UIViewController和UIView都是UIResponders ,负责处理事件。
To handle events, you need to override the touch* methods to do what you want. 要处理事件,您需要重写touch *方法以执行所需的操作。 To know what kind of touch events occurred, look at the UIEvent .
要了解发生了哪种触摸事件,请查看UIEvent 。
在你的init方法中:
self.userInteractionEnabled = YES;
Correction for madmik3, 对madmik3的更正,
you're missing the super call in your initWithFrame. 您在initWithFrame中缺少超级调用。
-(id) initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.userInteractionEnabled = YES;
} return self;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.