iosswifttvosuiswipegesturerecognizer

UISwipeGestureRecognizer on tvOS is giving me a EXC_BAD_ACCESS


I'm trying to add gesture code for swipe up/down to my UIViewController in a tvOS app.

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

When I run this I get a

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

on the let swipeDown line in the loadView function.

I'm using Xcode 11. What am I missing here?


Solution

  • Yeah, missing super.loadView() in your code also, you should create the gestures in viewDidLoad instead 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
          }
        }
      }