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");
    }
    
    
  • 附代码链接:
    UIViewExtensionBlock


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,152评论 5 13
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,595评论 6 30
  • 代码创建UIWindow对象 Xcode7之后使用代码创建UIWindow对象: //创建UIWindow对象 s...
    云之君兮鹏阅读 1,404评论 0 2
  • 在开发android中,当你需要引用第三方架包的时候你只需要在build.gradle简单的配置一下就可以使用了。...
    区区一只yamada阅读 489评论 0 6
  • 我从小是个一根筋的人。 好比做家务,明明可以边拖地边把衣服放洗衣机洗,可我却偏要一件事做完了再做另外一件,...
    简繁君阅读 426评论 3 4