我想在我的按钮处于焦点时执行某些操作,而不是在
tvOS
中手动点击它。
我有四个水平排列的 UIButton,当用户只关注 4 个按钮之一时,我将显示一个包含一些信息的 UIView。
如何在无需单击按钮的情况下执行操作?
当其中一个按钮成为焦点视图时,您可以执行操作。
您可以为每个按钮分配一个标签,并使用聚焦按钮的标签来确定要执行的操作。为了便于阅读,您可以定义一个包含每个标签值的
enum
。
enum FocusedButtonTag: Int {
case First // Substitute with names that correspond to button's title/action
case Second
case Third
case Fourth
}
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator)
guard let button = UIScreen.mainScreen().focusedView as? UIButton else {
return
}
// Update your UIView with the desired information based on the focused button
switch button.tag {
case FocusedButtonTag.First.rawValue:
... // first button's action
case FocusedButtonTag.Second.rawValue:
... // second button's action
case FocusedButtonTag.Third.rawValue:
... // third button's action
case FocusedButtonTag.Fourth.rawValue:
... // fourth button's action
default:
break
}
}
override func didUpdateFocus(in ctx: UIFocusUpdateContext,
with anco: UIFocusAnimationCoordinator) {
super.didUpdateFocus(in: ctx, with: anco)
if ctx.nextFocusedView == yourButton { .. }
if ctx.nextFocusedView == yourOtherButton { .. }
}