自定义UILabel,接受触摸事件

1 #import <UIKit/UIKit.h>
2 
3 @interface myLabel : UILabel
4 
5 @end

 

 1 #import "myLabel.h"
 2 
 3 @implementation myLabel
 4 
 5 - (id)initWithFrame:(CGRect)frame
 6 {
 7     self = [super initWithFrame:frame];
 8     if (self) {
 9         // Initialization code
10     }
11     return self;
12 }
13 
14 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
15     NSLog(@"myLabel touch");
16 }
17 
18 @end

 

 1 #import "ViewController.h"
 2 
 3 @implementation ViewController
 4 
 5 - (void)viewDidLoad
 6 {
 7     [super viewDidLoad];
 8     [self.view setBackgroundColor:[UIColor greenColor]];
 9     
10     myLabel *label = [[myLabel alloc] init];
11     label.frame = CGRectMake(60, 100, 200, 50);
12     label.text = @"Hello world";
13     label.backgroundColor = [UIColor blueColor];
14     
15     label.userInteractionEnabled = YES;
16     
17     [self.view addSubview:label];
18 }

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

  20    NSLog(@"viewController touch");

  21 }

 

如果label.userInteractionEnabled = NO; (默认值),当用户点击label时将显示“viewController touch”。

 

如果在myLabe中加入:

1 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
2     NSLog(@"myLabel touch");
3     [self.nextResponder touchesBegan:touches withEvent:event];  // 接受到事件后继续向上传递事件
4 }

 

posted @ 2013-02-19 14:45  diablo大王  阅读(2558)  评论(0编辑  收藏  举报