我有一个视图的集合,我想当它们被点击时,它将执行相同的segue。没有视图执行任何segue。
class ViewController: UIViewController {
@IBOutlet var categoryViews: [UIView]!
let tapGesture = UIGestureRecognizer(target: self, action: #selector(ViewController.move(tap:)))
override func viewDidLoad() {
super.viewDidLoad()
for category in (0..<categoryViews.count) {
categoryViews[category].addGestureRecognizer(tapGesture)
categoryViews[category].isUserInteractionEnabled = true
}
// Do any additional setup after loading the view.
}
@objc func move(tap: UIGestureRecognizer) {
performSegue(withIdentifier: "Animals", sender: nil)
}
}
最佳答案
可以将UITapGestureRecognizer
的单个实例添加到单个视图中。
在您的代码中,由于您对每个视图使用UITapGestureRecognizer
的单个实例,因此tapGesture
将只添加到view
categoryViews
中的最后一个array
中。
您需要为UITapGestureRecognizer
中的每个view
创建不同的categoryViews
实例,即。
class ViewController: UIViewController {
@IBOutlet var categoryViews: [UIView]!
override func viewDidLoad() {
super.viewDidLoad()
categoryViews.forEach {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(move(tap:)))
$0.addGestureRecognizer(tapGesture)
$0.isUserInteractionEnabled = true
}
}
@objc func move(tap: UITapGestureRecognizer) {
performSegue(withIdentifier: "Animals", sender: nil)
}
}