tvOS 上的 UISwipeGestureRecognizer 给了我 EXC_BAD_ACCESS

UISwipeGestureRecognizer on tvOS is giving me a EXC_BAD_ACCESS

我正在尝试在 tvOS 应用程序中向我的 UIViewController 添加用于滑动 up/down 的手势代码。

    override func loadView() {
        let swipeDown = UISwipeGestureRecognizer(
            target: self,
            action: #selector(self.respondToSwipeGesture)
        )
        swipeDown.direction = UISwipeGestureRecognizer.Direction.down
        self.view.addGestureRecognizer(swipeDown)

        let swipeUp = UISwipeGestureRecognizer(
            target: self,
            action: #selector(self.respondToSwipeGesture)
        )
        swipeUp.direction = UISwipeGestureRecognizer.Direction.up
        self.view.addGestureRecognizer(swipeUp)
    }

    @objc private func respondToSwipeGesture(gesture: UIGestureRecognizer) {
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
            switch swipeGesture.direction {
                case UISwipeGestureRecognizer.Direction.down:
                    print("Swiped down")
                case UISwipeGestureRecognizer.Direction.up:
                    print("Swiped up")
                default:
                    break
            }
        }
    }

当我 运行 这个我得到一个

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee7146fe8)

loadView 函数的 let swipeDown 行。

我正在使用 Xcode 11. 我在这里缺少什么?

是的,您的代码中也缺少 super.loadView(),您应该在 viewDidLoad 而不是 loadView 中创建手势。

  override func loadView() {
    super.loadView() // ---> In this case always in the second line
    let swipeDown = UISwipeGestureRecognizer(
      target: self,
      action: #selector(self.respondToSwipeGesture)
    )
    swipeDown.direction = UISwipeGestureRecognizer.Direction.down
    self.view.addGestureRecognizer(swipeDown)

    let swipeUp = UISwipeGestureRecognizer(
      target: self,
      action: #selector(self.respondToSwipeGesture)
    )
    swipeUp.direction = UISwipeGestureRecognizer.Direction.up
    self.view.addGestureRecognizer(swipeUp)
  }

  @objc private func respondToSwipeGesture(gesture: UIGestureRecognizer) {
    if let swipeGesture = gesture as? UISwipeGestureRecognizer {
      switch swipeGesture.direction {
      case UISwipeGestureRecognizer.Direction.down:
        print("Swiped down")
      case UISwipeGestureRecognizer.Direction.up:
        print("Swiped up")
      default:
        break
      }
    }
  }

您覆盖了错误的方法:

override func loadView() {

你的意思是:

override func viewDidLoad() {