UIFocusGuide UITableView 和 UIButton

UIFocusGuide UITableView and UIButton

我很难创建将从 UITableView 跳转到 UIButton 的 UIFocusGuide。这是调试器上下文屏幕截图:

这是实现:

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
        }

    }

当我位于 UITableView 的中间项或 UITableView 的末尾时,didUpdateFocusInContext 函数永远不会被调用。

将焦点指南添加到按钮而不是 self.view。您不需要覆盖 didUpdateFocusInContext 例如:

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
}