2009-12-04 80 views
2

如何使用代碼(無Interface Builder)在UIviewController中檢測UIView中的觸摸?使用界面生成器檢測UIView上的觸摸

我發現了touchesBegan方法,但它不會被調用。我沒有初始化關於這種方法的其他任何內容。

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

的touchesBegan是的UIView的一部分,你必須啓用接觸,以獲得接觸到ViewController你應該擁有的觀點告訴觸摸的C ontroller – Daniel 2009-12-04 16:29:18

+0

感謝好友。這非常有幫助......! – 2011-07-01 07:14:58

回答

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 
+0

你好@ madmik3。好的片段,但我怎樣才能分配代表? – 2011-04-28 00:14:28

+2

該屬性應該使用「分配」不保留。 設置代表 TouchView * tv = ....; tv.delegate = self; ... – 2011-07-21 20:30:45

0

在您的init方法:

self.userInteractionEnabled = YES; 
0

修正爲madmik3,

你缺少你initWithFrame超級調用。

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