iosswiftuitabbarcontrolleruiresponderbecomefirstresponder

UITabBarController canBecomeFirstResponder method not get called


After reading http://nshipster.com/uikeycommand/ i wanted to add navigation between tabs using arrow keys to my app. But i cuold not managed to receive key presses within UITabBarController. Same code block below works within UIViewController but UITabBarController.

When i tried to debug, canBecomeFirstResponder override for UITabBarController not even get called. I did not find something useful on apple s docs. Appreciate any information which makes the problem clear.

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    let firstResponderResult = self.becomeFirstResponder()
    println("became first responder \(firstResponderResult)")
}

override func canBecomeFirstResponder() -> Bool {
    return true
}

override var keyCommands: [AnyObject]? {
    return [
        UIKeyCommand(input: UIKeyInputRightArrow, modifierFlags: UIKeyModifierFlags.allZeros, action: "rightArrowClicked:"),
        UIKeyCommand(input: UIKeyInputLeftArrow, modifierFlags: UIKeyModifierFlags.allZeros, action: "leftArrowClicked:")
    ]
}

func rightArrowClicked(sender: UIKeyCommand) {

    let currentIndex = selectedIndex;

    if (currentIndex < viewControllers!.count - 1) {
        selectedIndex = currentIndex + 1;
    }
}

func leftArrowClicked(sender: UIKeyCommand) {
    let currentIndex = selectedIndex;

    if (currentIndex > 0) {
        selectedIndex = currentIndex - 1;
    }
}

Solution

  • I think you should override canBecomeFirstResponder method of VC's inside the UITabBarController, not the tab bar controller's. This way you should be able to get key presses.