UIFocusGuide 사용법 - tvOS -

tvOS Advent Calendar 2017 4일째 담당 @에서 카토 토로 입니다.

오늘은 UIFocusGuide를 사용하는 방법에 관한 것입니다.

포커스



첫째, 쉽게 초점을 설명합니다.

iOS와 tvOS의 가장 큰 차이점으로 포커스가 있습니다.
iOS 기기의 경우, 사용자는 직접 터치 스크린상에서 조작하지만 Apple TV에서는 리모컨으로 화면상의 어느 항목으로 이동하면 “포커스된 상태가 되어 사용자 액션의 대상이 된다는 동작이 된다. 합니다.

초점을 맞춘 View는 포커스 엔진을 결정합니다. 포커스 엔진이 검색하는 범위는 현재 포커스가 있는 View의 크기에 따라 결정되며, 그 View를 기점으로 하여 좌우 상하로 움직임 방향에 있는 포커스 가능한 영역을 찾아 갱신합니다.

포커스 엔진은 View 계층 구조의 포커스 동작을 정의하는 UIFocusEnvironment 프로토콜에 따라 포커스를 제어하지만 UIFocusGuide를 사용하면 포커스 엔진이 포커스하는 View를 동적으로 지정할 수 있습니다.

UIFocusGuide



UIFocusGuide는 포커스를 위한 가이드입니다.
UILayoutGuide 를 상속한 클래스로, 포커스용으로 preferredFocusEnvironments 가 정의되고 있습니다.
@available(tvOS 9.0, *)
open class UIFocusGuide : UILayoutGuide {


    /// If disabled, UIFocusGuides are ignored by the focus engine, but still participate in layout. Modifying this flag allows you to conditionally enable or disable certain focus behaviors. YES by default.
    open var isEnabled: Bool


    /// Setting preferredFocusEnvironments to a non-empty array marks this guide's layoutFrame as focusable. If empty, this guide is effectively disabled.
    /// If focused, the guide attempts to redirect focus to each environment in the array, in order, stopping when a focusable item in an environment has been found.
    @available(tvOS 10.0, *)
    open var preferredFocusEnvironments: [UIFocusEnvironment]!

}


UIFocusGuide 사용법



구체적인 예로 UIFocusGuide의 사용법을 설명하고 싶습니다.
다음과 같은 UIButton과 UICollectionView의 간단한 화면을 예로 들어 보겠습니다.


1번 왼쪽의 collectionCell에서 button에의 포커스는 할 수 있습니다만


두 번째 이후의 collectionCell에서 버튼으로의 포커스는 기본적으로 불가능합니다.


이것은 포커스 엔진이 검색하는 범위는 현재 포커스되고 있는 View의 크기에 따라 결정되기 때문입니다.
이 경우 FocusGuide를 사용하여 포커스를 제어할 수 있습니다.
FocusGuide를 추가해 보겠습니다.

@IBOutlet private weak var button: UIButton!
@IBOutlet private weak var collectionView: UICollectionView!
private let focusGuide = UIFocusGuide()
...
override func viewDidLoad() {
    super.viewDidLoad()

    view.addLayoutGuide(focusGuide)

    focusGuide.topAnchor.constraint(equalTo: button.topAnchor).isActive = true
    focusGuide.leftAnchor.constraint(equalTo: collectionView.leftAnchor).isActive = true

    focusGuide.heightAnchor.constraint(equalTo: button.heightAnchor).isActive = true
    focusGuide.widthAnchor.constraint(equalTo: collectionView.widthAnchor).isActive = true

    focusGuide.preferredFocusEnvironments = [button]
    ...
}

그림으로 하면 다음과 같이 FocusGuide가 추가됩니다.


FocusGuide를 추가하면 두 번째 이후의 collectionCell에서 버튼으로 포커스가 가능합니다.


또한 focusGuide.preferredFocusEnvironments를 조건이나 포커스된 View에 의해 변경하는 등 동적으로 포커스를 제어할 수 있습니다.

요약



간단하지만, UIFocusGuide의 설명이었습니다.
포커스 엔진은 현재 포커스가 있는 View의 크기에 따라 좌우 상하의 범위에서 포커스 하는 View를 검색합니다. 기본은 포커스 엔진에 맡겨두면 좋지만, 디폴트로 포커스되지 않는 레이아웃의 경우나, 동적으로 포커스의 제어를 실시하고 싶은 경우 등에 UIFocusGuide를 사용하면 간단하게 구현할 수 있을 것 같네요. .

tvOS Advent Calendar 2017 내일은 다시 @toshi0383 그리고 「AVContentProposal은 정말 편리한 것인가」입니다!

좋은 웹페이지 즐겨찾기