业务场景:某个cell上有一个switch,点击switch可以改变cell显示状态,点击cell上除了switch的其他区域就push一个新页面出来。
当时遇到的问题:在cell的init方法中添加了push页面的手势
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.rx.tapGesture().when(.recognized).subscribe(onNext: {tap in
vc.present(toVC, animated: true)
}
}).disposed(by:rxDisposedBag)
}
实际上运行以后发现点击到switch上时会触发present事件 解决方案:CGRectContainsPoint方法结合 UIGestureRecognizer的location(in view: UIView?) -> CGPoint方法 判断location方法返回的point是否在switch的frame中 实现代码如下:
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.rx.tapGesture().when(.recognized).subscribe(onNext: {tap in
let tap1 : UITapGestureRecognizer = tap as UITapGestureRecognizer
if CGRectContainsPoint(self.switch.frame, tap1.location(in:self)){
return
}
vc.present(toVC, animated: true)
}
}).disposed(by:rxDisposedBag)
}