UIView擴(kuò)展添加點擊事件
在app開發(fā)過程中服傍,面對炫酷的界面設(shè)計,不僅圖片文字能點擊就連空白區(qū)域也要能點擊骂铁,面對這種場景解決方案當(dāng)然是添加各種手勢吹零、或者在上面再添加一層button/control之類的,每個控件都要這樣寫一遍太煩了拉庵,灿椅,,下面通過UIView類的擴(kuò)展用兩種方式钞支,一句話為空間添加可點擊事件阱扬。
UIView類擴(kuò)展,添加Block/target-action 事件回調(diào)
-
添加 Block 事件:
- (void)addActionWithblock:(TouchCallBackBlock)block;
-
添加 Target-Action 事件:
- (void)addTarget:(id)target action:(SEL)action;
-
使用例子:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = [UIColor whiteColor]; // UIView 添加 Block 事件: UIView *view = [[UIView alloc] initWithFrame:CGRectMake(50, 100, 100, 100)]; view.backgroundColor = [UIColor blueColor]; [self.view addSubview:view]; [view addActionWithblock:^{ NSLog(@"view 被點擊 ......\n"); }]; //UILabel 添加 Block 事件: UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(180, 100, 100, 100)]; label.backgroundColor = [UIColor redColor]; [self.view addSubview:label]; [label addActionWithblock:^{ NSLog(@"label 被點擊 ......\n"); }]; // UIImageView 添加 Block 事件: UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 250, 100, 100)]; imageView.backgroundColor = [UIColor purpleColor]; [self.view addSubview:imageView]; [imageView addActionWithblock:^{ NSLog(@"imageView 被點擊 ......\n"); }]; // UIImageView 添加 Target-Action 事件: UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(180, 250, 100, 100)]; imageView2.backgroundColor = [UIColor brownColor]; [self.view addSubview:imageView2]; [imageView2 addTarget:self action:@selector(imageDidSelcte:)]; } - (void)imageDidSelcte:(id)sender { NSLog(@" targetAction label 被點擊 ......\n"); }
附代碼鏈接:
UIViewExtensionBlock