使用Interface Builder检测UIView上的触摸

时间:2009-12-04 16:20:58

标签: iphone cocoa-touch uiview

如何仅使用代码(没有Interface Builder)检测UIviewControllerUIView的触摸?

我找到了touchesBegan方法,但它永远不会被调用。我没有初始化有关此方法的任何其他内容。

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

4 个答案:

答案 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

UIViewControllerUIView都是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;
}