I created a UITabBarController with multiple view controllers. To the view controllers I added an UIPanGestureRecognizer to the UIWindow.

This works correctly.

Problem: Whenever I change the selectedIndex in viewWillAppear in the UITabBarController (to show the last opened tab), the correct view controller will be displayed, but the added panGestureRecognizer to the window is not working.

When I change the selected tab manually the window panGestureRecognizer works. This happens every app start.

What's the problem? (Xcode 10.2.1, Swift 5)

Thanks in advance!

// UITabBarController
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if UserDefaults.standard.object(forKey: self.selectedTabIndexKey) != nil {
        selectedIndex = UserDefaults.standard.integer(forKey: self.selectedTabIndexKey)
    }
}


// ViewController2
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let window = appDelegate.window {
        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
        window.isUserInteractionEnabled = true
        window.addGestureRecognizer(panGestureRecognizer)
    }
}


@objc fileprivate func handlePan(gesture: UIPanGestureRecognizer) {
    // ...
}

1 Answers

0
Michael On

After cleaning, rebuilding the Xcode project and putting the selectedIndex in viewDidLoad it finally works.

override func viewDidLoad() {
    super.viewDidLoad()

    viewControllers = [
        vc1,
        vc2
    ]

    if UserDefaults.standard.object(forKey: self.selectedTabIndexKey) != nil {
        selectedIndex = UserDefaults.standard.integer(forKey: self.selectedTabIndexKey)
    }
}