swift - View 不执行 segue

标签 swift xcode

我有一个 View 集合,我想在点击它们时执行相同的 segue。并且没有 View 执行任何 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 的单个实例可以添加到单个 View 。

在您的代码中,因为您使用的是 UITapGestureRecognizer 的单个实例对于每个 View ,tapGesture将仅添加到最后viewcategoryViews array .

您需要创建不同的 UITapGestureRecognizer每个实例 viewcategoryViews ,即

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)
    }
}

关于swift - View 不执行 segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56810329/

相关文章:

ios - 多次调用一个 Alamofire 请求,获取每次调用的引用

iphone - 我如何使用 CoreGraphics 绘制半圆

iphone - 使用静态库打包 Bundle

xcode - Settings.bundle问题

ios - 仅从包含数字的句子中提取单词

ios - 我在 iOS 上有一个 Objective-C 应用程序,如何构建 Swift Watch 扩展?

ios - 我的 iOS 开发者证书或私钥在 git 中吗?

iphone - 为较旧的 SDK 部署 iOS 应用程序时,如何测试它?

iOS:将 IBAction 添加到 UILabel 的一部分

swift - 如何停止后台更新任务?