如何在tvOS中检测祖先是否被聚焦?

问题描述 投票:1回答:2

我有一个自定义的 UIView 子类,并希望检测其祖先何时被聚焦。但是这个类本身不能被聚焦。

基本上,我想做一些类似于 UIImageViewadjustsImageWhenAncestorFocused 被设置为true。

我希望有一个解决方案,不需要祖先在焦点变化时进行通信。

uikit tvos
2个回答
0
投票

你可以实现didUpdateFocusInContext,检查目标视图是否是你的祖先。

  override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) 
  {
      if let target = context.nextFocusedView
         where self.isDescendantOfView(target)
      {
         // one of your ancestors has received focus 
      }
  }    

0
投票

我们不能使用 didUpdateFocus(in:with:)的方法,因为它并不是对所有层次结构的视图都被调用的,从文档中可以看出。

聚焦引擎会在所有的焦点环境中调用这个方法,这些环境包含之前的焦点视图,下一个焦点视图,或者两者都包含。

所以,如果视图返回 false 对于 canBecomeFocused,这个方法不能对它进行调用。

适当的方法是观察 UIFocusSystem.didUpdateNotification如果你用的是Combine,就像这样。

NotificationCenter.default.publisher(for: UIFocusSystem.didUpdateNotification).sink { [weak self] notification in
    guard let context = notification.userInfo?[UIFocusSystem.focusUpdateContextUserInfoKey] as? UIFocusUpdateContext,
        let next = context.nextFocusedView, self?.isDescendant(of: next) ?? false else {
            print("is NOT descendant")
            return
    }

    print("is descendant")
}.store(in: &cancelBag)
© www.soinside.com 2019 - 2024. All rights reserved.