如何强制焦点更改为tvOS中的特定视图?

Sim*_*sen 13 objective-c tvos

我正在实现自定义代码来处理Siri Remote上菜单按钮的点击.按菜单按钮时如何强制焦点更改为我的自定义菜单?

Sla*_*ter 19

终于弄清楚了自己.你必须覆盖preferredFocusedViewUIView或你的属性UIViewController.

在swift中,它是这样的:

func myClickHandler() {
    someCondition = true
    self.setNeedsFocusUpdate()
    self.updateFocusIfNeeded()
    someCondition = false
}

override weak var preferredFocusedView: UIView? {
    if someCondition {
        return theViewYouWant
    } else {
        return defaultView
    }
}
Run Code Online (Sandbox Code Playgroud)

我不太清楚如何在Objective-C中覆盖getter,所以如果有人想发帖,我会编辑答案.

  • 我同意.希望他们会添加它.另外为了避免所有的`someCondition`,我在viewController中添加了一个`viewToFocus``UIView`属性.然后在getter中,我检查该视图是否为nil并返回它.否则返回默认视图. (2认同)

vik*_*ati 17

对于ios 10,您应该使用preferredFocusEnvironments而不是preferredFocusedView.

在下面的示例中,如果您想关注btnEnglish,请参阅下面的代码.

@IBOutlet weak var button: UIButton!

override var preferredFocusEnvironments: [UIFocusEnvironment] {
    return [button]
}

override func viewDidLoad() {
    super.viewDidLoad()

    setNeedsFocusUpdate()
    updateFocusIfNeeded()
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是现在接受的答案,因为`preferredFocusedView`正在折旧. (2认同)

小智 15

这是基于Slayters上面的答案的另一个实现.我认为它比使用条件布尔值更优雅.

把它放在你的viewcontroller中

var viewToFocus: UIView? = nil {
    didSet {
        if viewToFocus != nil {
            self.setNeedsFocusUpdate();
            self.updateFocusIfNeeded();
        }
    }
}

override weak var preferredFocusedView: UIView? {
    if viewToFocus != nil {
        return viewToFocus;
    } else {
        return super.preferredFocusedView;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的代码中使用它

viewToFocus = myUIView;
Run Code Online (Sandbox Code Playgroud)


Jen*_*ers 6

这是目标C.

- (UIView *)preferredFocusedView
{
    if (someCondition) {
      // this is if your menu is a tableview
        NSIndexPath *ip = [NSIndexPath indexPathForRow:2 inSection:0];
        UITableViewCell * cell = [self.categoryTableView cellForRowAtIndexPath:ip];

        return cell;
    }

    return self.view.preferredFocusedView;

}
Run Code Online (Sandbox Code Playgroud)

在你的viewDidLoad或视图确实出现过这样的事情:

    UIFocusGuide *focusGuide = [[UIFocusGuide alloc]init];
    focusGuide.preferredFocusedView = [self preferredFocusedView];
    [self.view addLayoutGuide:focusGuide];
Run Code Online (Sandbox Code Playgroud)

如果你想在第一次启动时这样做