如何为自定义视图设置 canBecomeFocused

How do you set canBecomeFocused for a custom view

我正在申请 tvOS。我有一个包含 UIButton 的视图和一个包含其他几个自定义视图的自定义 UIView。模拟器只能突出显示 UIButton 而不是自定义视图。

根据 Building Apple TV Apps Docs:

If your custom view needs to be focusable, override canBecomeFocused to return YES (by default, it returns NO).

根据canBecomeFocused Docs

canBecomeFocused 将 return

YES if the view can become focused; NO otherwise.

但是,尝试通过这样做将 YES 分配给 canBecomeFocused:

self.customView.canBecomeFocused = YES;

出现此错误:

No setter method 'setCanBecomeFocused:' for assignment to property

我该如何完成?

看起来 UIView 声明了 function/property。

你试过像这样覆盖函数吗?

Swift

override func canBecomeFocused() -> Bool {
    return true
}

Objective-C

- (BOOL)canBecomeFocused {
    return YES;
}

我没试过这个,但它可能对你有用。

除了在您的自定义视图中重写 canBecomeFocused 方法:

override func canBecomeFocused() -> Bool {
    return true
}

确保您的自定义视图 userInteractionEnabled 正确。这是确保您的视图可以聚焦的完整列表:

Why Is This View Not Focusable?

There are a number of reasons a view that is expected to be focusable may not be, including (but not limited to):

  • The view’s canBecomeFocused method returns NO.
  • The view’s hidden property has a value of YES.
  • The view’s alpha property has a value of 0.
  • The view’s user interaction is disabled.
  • The view is obscured by another view on top of it.

我的 customView 代码块上面的答案还不够。

Swift

import UIKit

class Focus: UIView {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */

    override func canBecomeFocused() -> Bool {
        return true
    }

    override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
        if context.previouslyFocusedView === self {
            UIView.animateWithDuration(0.1, animations: { () -> Void in
                context.previouslyFocusedView?.transform = CGAffineTransformMakeScale(1.0, 1.0)
            })
        }

        if context.nextFocusedView === self {
            UIView.animateWithDuration(0.1, animations: { () -> Void in
                context.nextFocusedView?.transform = CGAffineTransformMakeScale(1.4, 1.4)
            })
        }
    }
}