如何仅使用代码(没有Interface Builder)检测UIviewController
中UIView
的触摸?
我找到了touchesBegan方法,但它永远不会被调用。我没有初始化有关此方法的任何其他内容。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
答案 0 :(得分:6)
#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
答案 1 :(得分:1)
我会阅读iPhone应用程序编程指南的Touch Events sections。
UIViewController和UIView都是UIResponders,负责处理事件。
要处理事件,您需要覆盖touch *方法以执行您想要的操作。要了解发生了什么类型的触摸事件,请查看UIEvent。
答案 2 :(得分:0)
在你的init方法中:
self.userInteractionEnabled = YES;
答案 3 :(得分:0)
对madmik3的更正,
你错过了initWithFrame中的超级调用。
-(id) initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.userInteractionEnabled = YES;
} return self;
}