在我的主窗口的根视图控制器类中,我设置了一个UITapGestureRecognizer属性.在调用重写的viewDidLoad函数期间,我已通过addGestureRecognizer方法将此属性添加到图像属性.我还将image.isUserInteractionEnabled设置为true.
override func viewDidLoad() {
image.addGestureRecognizer(tap)
image.isUserInteractionEnabled = true
self.view.addSubview(image)
}
var tap = UITapGestureRecognizer(target: self, action: #selector(imagePressed(_ :)))
遗憾的是,这不会导致运行时调用imagePressed().令我困惑的是,以下代码产生了预期的结果.
override func viewDidLoad() {
var tap = UITapGestureRecognizer(target: self, action:#selector(imagePressed(_ :)))
image.addGestureRecognizer(tap)
image.isUserInteractionEnabled = true
self.view.addSubview(image)
}
所以我的问题是,为什么在第一种情况下不会调用UITapGestureRecognizer的选择器?
使用Swift 3和Xcode 8.2.1
最佳答案 我认为这里的问题是addGestureRecognizer.
尝试将viewDidLoad更改为:
override func viewDidLoad() {
var tap = UITapGestureRecognizer(target: self, action:#selector(imagePressed(_ :)))
image.isUserInteractionEnabled = true
self.view.addSubview(image)
image.addGestureRecognizer(tapGesture)
}