开发者

Detect touch on UIView with Interface Builder

How can I detect touches in a UIviewController for a UIView with code only (without Interface Builder)?

I found the touchesBegan method but it doesn't get called ever. I didn't initialize anything else regarding this method.

-(void)touchesBegan:(NSSet *)touches wi开发者_Go百科thEvent:(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.

UIViewController and UIView are both UIResponders, which is responsible for handling the events.

To handle events, you need to override the touch* methods to do what you want. To know what kind of touch events occurred, look at the UIEvent.


In your init method:

self.userInteractionEnabled = YES;


Correction for madmik3,

you're missing the super call in your initWithFrame.

-(id) initWithFrame:(CGRect)frame {
 if (self = [super initWithFrame:frame]) {
 self.userInteractionEnabled = YES;
 }  return self;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜