问题
I am making an application for tvOS. I have a view that contains a UIButton
and a custom UIView
that contains a couple other custom views. The simulator is only able to highlight the UIButton
and not the custom view.
According to the Building Apple TV Apps Docs:
If your custom view needs to be focusable, override canBecomeFocused to return YES (by default, it returns NO).
According to the canBecomeFocused Docs:
canBecomeFocused will return
YES if the view can become focused; NO otherwise.
However, attempting to assign YES to canBecomeFocused by doing this:
self.customView.canBecomeFocused = YES;
Gives this error:
No setter method 'setCanBecomeFocused:' for assignment to property
How do I accomplish this?
回答1:
It looks like UIView
declares the function/property.
Have you tried overriding the function like so?
Swift
override func canBecomeFocused() -> Bool {
return true
}
Objective-C
- (BOOL)canBecomeFocused {
return YES;
}
I haven't tried this, but it may work for you.
回答2:
Besides of overriding the canBecomeFocused
method in your custom view:
override func canBecomeFocused() -> Bool {
return true
}
Make sure your custom view userInteractionEnabled
is true. This is the complete list to be sure your view can be focused:
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.
回答3:
Above answers are not enough this my customView code block.
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)
})
}
}
}
来源:https://stackoverflow.com/questions/32753109/how-do-you-set-canbecomefocused-for-a-custom-view