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

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

当我运行这个我得到一个

线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x7ffee7146fe8)

let swipeDown函数的loadView行上。

我正在使用Xcode11。我在这里想念什么?

最佳答案

是的,在代码中也缺少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
      }
    }
  }

关于ios - tvOS上的UISwipeGestureRecognizer给了我EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58179110/

10-10 22:41