简介
手势冲突 肯定不少人遇到过, 并且应该都是以 bug 的形式出现的.
我以前第一次遇到的时候也挺头疼.但是今天我要利用这个 bug 的原理来完成一个工作中遇到的需求.
正文
前几天拿到一张 UI 设计图, 如图:

看到这张设计图我的第一反应就是利用
UITableView
来写页面布局, 上面3张卡片用 UITableViewCell
写, 底部的 个人信息
和 button
全部写在 FooterView
上.
于是快速的按照一开始的想法把页面撸了出来了, 效果看起来跟效果图也一模一样.
然而美中不足的就是点击的时候整个 cell
点击都有效果. 当然有大把的办法来解决这个问题, 比如使用 delegate
, block
都可以. 但是在强迫症的驱使下, 既然使用了 UITableView
, 我更加倾向于使用 UITableViewDelegate
协议的方法来处理 cell
的点击事件.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
但是这样就必须解决 cell
被点击时候的有效点击范围, 也就是只有图片范围内点击时候才会调用 didSelectRowAtIndexPath
, 点击其他空白部分不会被回调.
于是第一时间就想到以前因为添加自定义手势而导致 cell
本身点击 didSelectRowAtIndexPath
不会回调的问题.
于是按照以前写出 bug 的办法来搞 😉
首先给 cell.contentView
添加自定义手势:
// 利用手势冲突, 配合代理方法限制有效点击范围在 card 内
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
tap.delegate = self;
[self.contentView addGestureRecognizer:tap];
然后实现 tap
手势触发的回调方法:
#pragma mark - Action
- (void)tapAction {
NSLog(@"%s", __func__);
}
实现 tap
的代理方法:
通过
tap
的delegate
方法来区分触发手势时候, 被点击到的视图
如果点击的是图片, 也就是resultImageView
则返回NO
, 该次点击会被忽略, 把点击事件传递到下一级视图进行处理, 则此时didSelectRowAtIndexPath
会被调用
#pragma mark - UIGestureRecognizer delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if ([touch.view isEqual:_resultImageView]) {
return NO;
}
return YES;
}
以下是 didSelectRowAtIndexPath
方法:
// row select
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSLog(@"%s", __func__);
if (indexPath.row == 0) {
// 正面
} else if (indexPath.row == 1) {
// 反面
} else {
// 人脸识别
}
}
验证
点击 cell
的空白位置

控制台打印:

点击 图片 的 卡片 区域

控制台打印如图:

结果
看结果来说, 这样的做法的确是达到起初的目的:
只有点击卡片时候, 让
didSelectRowAtIndexPath
被回调, 其他部分点击无效.
想要达到同意的目的, 方法并不是唯一的, 类似的比如还有下面这个方法也可以达到一样的效果:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
文内这样的做法只是我临时脑内闪过的想法, 也就是想利用以前遇到的 bug
来解决一下当前的需求, 于是就做来试试, 验证一下想法.
网友评论