Make UILabel focusable and tappable (tvOS)

后端 未结 4 871
我在风中等你
我在风中等你 2021-01-12 20:45

I\'m trying to implement 6 lines high description label and I want it to be focusable. Ideally that would mean extending UILabel class to make a custom component. I tried th

4条回答
  •  渐次进展
    2021-01-12 20:56

    As for making a UILabel focusable:

    class MyLabel: UILabel {
    
        override var canBecomeFocused: Bool {
            return true
        }
    
        override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
            super.didUpdateFocus(in: context, with: coordinator)
    
            backgroundColor = context.nextFocusedView == self ? .blue:.red
    
        }
    }
    

    IMPORTANT!!! As stated on the apple developer portal:

    The value of this property is true if the view can become focused; false otherwise.

    By default, the value of this property is false. This property informs the focus engine if a view is capable of being focused. Sometimes even if a view returns true, a view may not be focusable for the following reasons:

    • The view is hidden.

    • The view has alpha set to 0.

    • The view has userInteractionEnabled set to false.

    • The view is not currently in the view hierarchy.

提交回复
热议问题