Search code examples
iosswiftuitableviewtvos

UIFocusGuide UITableView and UIButton


I am having a hard time creating a UIFocusGuide that will jump from the UITableView to a UIButton. Here is the debugger context screenshot:

enter image description here

And here is the implementation:

override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.delegate = self
        self.tableView.dataSource = self

        // add the focus guide
        self.view.addLayoutGuide(focusGuide)

        // add the anchors
        self.focusGuide.leftAnchor.constraintEqualToAnchor(self.button.leftAnchor).active = true
        self.focusGuide.topAnchor.constraintEqualToAnchor(self.tableView.topAnchor).active = true
        self.focusGuide.widthAnchor.constraintEqualToAnchor(self.button.widthAnchor).active = true
        self.focusGuide.heightAnchor.constraintEqualToAnchor(self.tableView.heightAnchor).active = true
    }

    override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {

        guard let nextFocusedView = context.nextFocusedView else { return }

        switch nextFocusedView {
        case self.button:
            self.focusGuide.preferredFocusedView = self.button

        case self.tableView:
            self.focusGuide.preferredFocusedView = self.tableView

        default:
            self.focusGuide.preferredFocusedView = nil
        }

    }

The didUpdateFocusInContext function is never getting called when I am at the middle item of the UITableView or the end of the UITableView.


Solution

  • Add the focus guide to the button not self.view. You don't need override didUpdateFocusInContext For example:

    var focusGuide = UIFocusGuide()
    override func viewDidLoad() {
            super.viewDidLoad()
    
            self.tableView.delegate = self
            self.tableView.dataSource = self
    
            // add the focus guide
            self.button.addLayoutGuide(focusGuide)
    
            // add the anchors
            self.focusGuide.leftAnchor.constraintEqualToAnchor(self.button.leftAnchor).active = true
            self.focusGuide.topAnchor.constraintEqualToAnchor(self.tableView.topAnchor).active = true
            self.focusGuide.widthAnchor.constraintEqualToAnchor(self.button.widthAnchor).active = true
            self.focusGuide.heightAnchor.constraintEqualToAnchor(self.tableView.heightAnchor).active = true
    }