您的当前位置:首页正文

UIView扩展添加点击事件

来源:花图问答

UIView扩展添加点击事件


在app开发过程中,面对炫酷的界面设计,不仅图片文字能点击就连空白区域也要能点击,面对这种场景解决方案当然是添加各种手势、或者在上面再添加一层button/control之类的,每个控件都要这样写一遍太烦了,,,下面通过UIView类的扩展用两种方式,一句话为空间添加可点击事件。

UIView类扩展,添加Block/target-action 事件回调

  • 添加 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");
    }