iOS 学习(一) 绑定事件

学习事件绑定方法。

直接对按钮组件进行绑定

Main.storyboard 中,拖拽组件到 implementation 中。唯一问题就是必须是可点击组件,其他组件不支持。

直接代码绑定触摸

使用 UITapGestureRecognizer 处理。也要注意,组件 userInteractionEnabled 需要是 YES

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController


- (void)viewDidLoad {
[super viewDidLoad];
[self setupView];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

- (void)setupView {
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(0, 20, 200, 50);
view.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:view];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
[label setText:@"tap here"];
[label setTextColor:[UIColor whiteColor]];
[view addSubview:label];

label.userInteractionEnabled = YES;
UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTouchUpInside:)];
[label addGestureRecognizer:labelTapGestureRecognizer];
}

- (void)labelTouchUpInside:(UITapGestureRecognizer *)recognizer {
NSLog(@"tap label,text(%@)", ((UILabel *) recognizer.view).text);
}

- (IBAction)buttonTouchUpInside:(id)sender {
NSLog(@"tap button");
}

@end