我有一个主视图和该主视图的4个子视图,它们都具有其UITapGestureRecognizer,当我点击一个子视图时,如何触发两个视图。以下示例,
如果我点击以查看1所需的日志,将是:
subview1 is clicked
MainView is clicked
我的代码
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let mainGesture = UITapGestureRecognizer(target: self, action: #selector(mainGestureActivated))
self.view.addGestureRecognizer(mainGesture)
let subGesture = UITapGestureRecognizer(target: self, action: #selector(subViewGestureActivated))
self.subview1.addGestureRecognizer(subGesture)
}
@objc func mainGestureActivated(){
print("MainView Clicked")
}
@objc func subViewGestureActivated(){
print("Subview Clicked")
}
仅打印单击的子视图!因为main正在封装其他手势,是否有可能触发两个手势识别器。
答案 0 :(得分:1)
首先,您应该在VC中遵循UIGestureRecognizerDelegate
,然后实现shouldRecognizeSimultaneouslyWith
的委托函数。在函数内部,应该检测gestureRecognizer
和otherGestureRecognizer
是否是您想要的,如果是,则应允许它们同时工作,
符合委托要求,并在viewDidLoad
之外声明手势识别器(因为稍后需要在委托方法中访问它们)。
var mainGestureRecognizer = UITapGestureRecognizer()
var subGestureRecognizer = UITapGestureRecognizer()
初始化您的识别器,并将您的VC设置为其代表:
mainGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(mainGestureActivated))
subGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(subViewGestureActivated))
mainGestureRecognizer.delegate = self
subGestureRecognizer.delegate = self
实现上述委托函数以允许同时识别subView和mainView:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == subGestureRecognizer && otherGestureRecognizer == mainGestureRecognizer {
return true
}
return false
}
如果希望它可用于4个不同的子视图,则应与其他方法一起检查委托方法中的语句。