首页 技术 正文
技术 2022年11月13日
0 收藏 678 点赞 5,151 浏览 1720 个字

如下:

CGRect imageRect = (CGRect){, , , };
UIImageView *imageView = [[[UIImageView alloc] initWithFrame:imageRect] autorelease];
imageView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:imageView];
UIButton *maskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
maskBtn.frame = imageView.bounds;
maskBtn.backgroundColor = [UIColor redColor];
[maskBtn addTarget:self action:@selector(maskBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
[imageView addSubview:maskBtn];

结果点击按钮不响应事件,小纠结了一下,在SO上得到信息:

UIImageView has userInteractionEnabled set to NO by default. You are adding the button as a subview to the image view. You should set it to YES.

所以,添加了一行代码,设置imageView响应用户交互即可:

CGRect imageRect = (CGRect){, , , };  UIImageView *imageView = [[[UIImageView alloc] initWithFrame:imageRect] autorelease];  imageView.backgroundColor = [UIColor yellowColor];  [self.view addSubview:imageView];  imageView.userInteractionEnabled = YES;
UIButton *maskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
maskBtn.frame = imageView.bounds;
maskBtn.backgroundColor = [UIColor redColor];
[maskBtn addTarget:self action:@selector(maskBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
[imageView addSubview:maskBtn];

这纯粹就是一个知识点引发的坑,因为以前在UIImageView上都是使用TapGesture来响应用户交互的,所以对这个坑没有太大印象 —— 我遇到过没?

上面代码所构建的视图层级大致如下:

UIImageView中的UIButton不响应事件解决方案

其中红色方框代表的是UIImageView上的UIButton按钮。

参考View Programming Guide for iOS文档,当用户在红色按钮上点击了一下后:

1. 硬件设施会通知UIKit有触摸事件;

2. UIKit将触摸事件信息封装成UIEvent对象,分发给合适的视图;

1) UIKit将事件对象放到当前App的事件队列中;

2) 参考Event Handling Guide for iOS文档,当前App会从事件队列取出一个事件对象,然后发送给key window对象;

3) key window对象通过Hit-Testing获取触摸事件发生时所在的视图对象;

4) 通过Hit-Testing获得的视图成为第一个可以响应事件的对象,first responder,如果它不响应,则事件对象会沿着响应者链传递。响应者链,即Responder Chain,是由first responder到当前App对象所构成的一串对象,它们都继承于UIResponder类;

P.S. 具体描述可以见此文档

3. 找到合适的处理事件的对象,比如上面代码是self(ViewController),响应事件做些事情;如果找不到就丢弃掉。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,086
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,561
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,410
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,183
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,820
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,903