bluefloyd8
bluefloyd8

Reputation: 2276

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

Upvotes: 2

Views: 8867

Answers (4)

johndpope
johndpope

Reputation: 5257

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

Upvotes: 0

madmik3
madmik3

Reputation: 6983

#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

Upvotes: 6

Ian Henry
Ian Henry

Reputation: 22413

In your init method:

self.userInteractionEnabled = YES;

Upvotes: 0

Ben S
Ben S

Reputation: 69392

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.

Upvotes: 1

Related Questions