Search code examples
swiftfocustvos

Differentiate between UIButton in didUpdateFocus()


Picture for reference

My MainViewController has 3 containers:

          | A | B | C| 

where A contains a tableView, B contains collectionView, and C contains an imageView. The tableView and imageView in A and C is hidden and should only be shown when focus is either on A or C. I have also two buttons(which is on top of the tableView and imageView) on A and C.

The problem that I'm having is whenever I'm moving focus from my collectionView to either A or C, xcode is unable to recognize if I'm going to either A or C. This is how my code looks like:

    override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
    super.didUpdateFocus(in: context, with: coordinator)

    if context.nextFocusedView is UIButton && context.previouslyFocusedView is UICollectionViewCell {
        print("Focus moved to left column")
        }
    }

How do I tell xcode that button in A is different from the button in C?


Solution

  • The easiest way might be to assign a tag to each button, like buttonA.tag = 1, buttonB.tag = 2 etc. Then in your didUpdateFocus... you can check which button it is by changing your code slightly, to something like this:

    if let button = context.nextFocusedView as? UIButton, context.previouslyFocusedView is UICollectionViewCell {
        switch button.tag {
        case 1:
            // This is button A.  Do whatever you need with that info
        case 1:
            // This is button B...
        etc.
        }
    }