简体   繁体   中英

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 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.

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 .

在你的init方法中:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM