iOS 学习(一) 绑定事件
· 阅读需 1 分钟
学习事件绑定方法。
直接对按钮组件进行绑定
在 Main.storyboard
中,拖拽组件到 implementation 中。唯一问题就是必须是可点击组件,其他组件不支持。
直接代码绑定触摸
使用 UITapGestureRecognizer
处理。也要注意,组件 userInteractionEnabled
需要是 YES
。
#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