我有一个视图的集合,我想当它们被点击时,它将执行相同的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将只添加到viewcategoryViews中的最后一个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)
    }
}

10-08 05:45
查看更多