티스토리 뷰

반응형

WWDC 2021 > SwiftUI Accessibility: Beyond the basics 를 보던 중, 

iOS15에 새로 나온 accessibilityRepresentation(representation:) 을 찾아보면서 좋은 예제를 발견해서 정리합니다. 

출처는 The power of accessibilityRepresentation view modifier in SwiftUI  글 입니다. 

 


 

[1]  accessibilityRepresentation(representation:) 

 

길게 눌렀을 때만 체크상태를 토글하는 LongPressCheckmark라는 커스텀 뷰를 만들었다고 해봅시다. 

import SwiftUI

struct LongPressCheckmark: View {
    @Binding var isSelected: Bool

    var body: some View {
        Image(systemName: isSelected ? "checkmark.rectangle" : "rectangle")
            .onLongPressGesture { isSelected.toggle() }
    }
}

 

 

위의 코드는 간단해보이지만, 접근성 지원을 하면 어떻게 될까요?!

VoiceOver가 이미지를 토글버튼처럼 인식하도록 하기 위해서 이렇게나 많은 코드를 추가해야합니다. 

import SwiftUI

struct LongPressCheckmark: View {
    @Binding var isSelected: Bool

    var body: some View {
        Image(systemName: isSelected ? "checkmark.rectangle" : "rectangle")
            .onLongPressGesture { isSelected.toggle() }
            .accessibilityRemoveTraits(.isImage)
            .accessibilityAddTraits(.isButton)
            .accessibilityAddTraits(isSelected ? .isSelected : [])
            .accessibilityLabel(Text("Checkmark"))
            .accessibilityHint("You can toggle the checkmark")
            .accessibilityAction { isSelected.toggle() }
    }
}

 

 

이 때,  accessibilityRepresentation(representation:) modifier를 쓰면 코드가 엄청 간단해집니다!

이 modifier는 accessibility element를 새로운 accessibility element로 대체하는 것으로

아래 코드에서는 VoiceOver가 Image를 Toggle로 인식하도록 대체한 것입니다. 

import SwiftUI

struct LongPressCheckmark: View {
    @Binding var isSelected: Bool

    var body: some View {
        Image(systemName: isSelected ? "checkmark.rectangle" : "rectangle")
            .onLongPressGesture { isSelected.toggle() }
            .accessibilityRepresentation {
                Toggle(isOn: $isSelected) {
                    Text("Checkmark")
                }
            }
    }
}



 

[2] accessibilityChildren(children:)

 

위에서 살펴본 accessibilityRepresentation이 accessibility element를 대체할 수 있는 것이라면

accessibilityChildren은 accessibility element의 children을 대체할 수 있는 것입니다. 

 

 

accessibilityRepresentation
accessibilityChildren

 

 

 

예를들어 BudgetHistoryGraph라는 CustomView가 있다고 해봅시다. 

 

 

VoiceOver 모드에서 그래프 안의 Line Bar children을 Rectangle (accessibility label과 value을 설정해준) 로 대체하고 싶을 때 

accessiblityChildren modifier 를 사용해줄 수 있는 것입니다. 

 

 

 

반응형
댓글