SwiftUI ActionSheet

2021년 7월 27일 수정

≡ 목차 (Table of Contents)

ActionSheet 사용하기

SwiftUI에서 ActionSheet를 띄우는 것은 약간 번거롭다. 함수를 호출해서 띄우는 방식이 아니라 스테이트 변화를 추적해서 액션 시트를 토글하는 방식으로 코딩해야 하기 때문이다.

아래 코드는 버튼을 누르면 액션 시트를 띄우는 단순한 뷰 예제이다. 컴파일러 도움 없이 손으로만 짠 코드라 오류가 있을 수 있다.

참고로 이 방법은 iOS 15, macOS Monterey에서 Deprecated 될 예정이다.

struct ContentView: View {
    @State private var showingActionSheet = false

    var body: some View {
        Button("Show ActionSheet") {
            showingActionSheet = true
        }
        .actionSheet(isPresented: $showingActionSheet) {
            ActionSheet(title: Text("Title"),
                        message: Text("Subtitle"),
                        buttons: [
                            .default(Text("Button 1")) {
                                print("Pressed Button 1")
                            },
                            .default(Text("Button 2")) {
                                print("Pressed Button 2")
                            },
                            .cancel(Text("Cancel"))
                            ])
        }
    }
}

showingActionSheet 스테이트는 액션 시트가 닫기면 자동으로 false 로 값이 세팅된다. 물론 취소(cancel) 버튼을 누른 경우도 마찬가지다.

.cancel() 항목에는 원하는 텍스트를 표시하게 할 수도 있다.

.cancel(Text("취소"))

취소 버튼(.cancel()) 자체는 옵셔널이라 아예 빼도 된다. 다만 빼면 당연하게도 취소 버튼이 안 나올 뿐이다.

관련된 주제들