我有一个自定义的UIView
子类,想要检测其祖先视图是否处于焦点状态。但是该类本身无法获得焦点。
基本上,我想要像UIImageView
一样,当设置adjustsImageWhenAncestorFocused
为true时执行某些操作。
我希望找到一种不需要祖先视图在焦点更改时进行通信的解决方案。
您可以实现 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
}
}
我们不能使用didUpdateFocus(in:with:)
,因为它不会被所有层次结构的视图调用,来自文档:
焦点引擎在包含先前聚焦视图、下一个聚焦视图或两者的所有焦点环境上调用此方法
因此,如果视图对canBecomeFocused
返回false
,则无法在其上调用此方法。
适当的方法是观察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)