SwiftUI

SwiftUI ActionSheets, Alert, Popover

Daesiker 2021. 2. 18. 10:03
반응형

Action Sheets

Action Sheets는 팝업 뷰의 종류 중 하나로 응답값에 대한 옵션이 2개 이상일 때 사용하기 좋다. macOS에서는 사용이 불가하고 iOS에서만 사용 가능하다.

 

import SwiftUI

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

    var body: some View {
        VStack {
            Button("Show action sheet") {
                self.showActionSheet = true
            }
        }.actionSheet(isPresented: $showActionSheet) {
            ActionSheet(
                title: Text("Actions"),
                message: Text("Available actions"),
                buttons: [
                    .cancel { print(self.showActionSheet) },
                    .default(Text("Action"),
                             action: nil),
                    .destructive(Text("Delete"))
                ]
            )
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

 

 

버튼을 만든뒤 .actionSheet라는 속성을 이용하여 ActionSheet를 만들 수 있다. .actionSheet의 파라미터인 isPresented는 Boolean형태이고 값이 true가 되면 해당 ActionSheet 창을 열 수 있게 도와준다.

 

Props

— title(String) : ActionSheet의 타이틀 명을 입력하는 공간이다.

— message(String) : ActionSheet에 대한 부가 설명을 입력하는 공간이다.

— buttons(Array) : 버튼의 개수와 종류를 배열 형식으로 입력한다. 버튼은 총 3가지가 있고 파라미터는 버튼 제목을 Text컴포넌트로 받는 것과 이벤트를 입력하는 action이라는 파라미터 총 2가지가 있다.

— .cancel() : actionSheet를 닫는 버튼이다.

— .default() : actionSheet의 기본값으로 acentColor로 표현한다.

— .destructive() : 버튼을 빨간색으로 표현한다.

 

 


Alert

ActionSheet와 같은 팝업 뷰를 보여주는 컴포넌트이다.

사용자가 앱 또는 시스템의 상태에 따라 조치를 취하기 원할 때 주로 사용한다.

 

import SwiftUI

struct ContentView: View {
    @State private var showAlert = false
    var body: some View {
        Button("Tap to show alert") {
            showAlert = true
        }
        .alert(isPresented: $showAlert) {
            Alert(
                title: Text("Unable to Save Workout Data"),
                message: Text("The connection to the server was lost."),
                primaryButton: .default(
                    Text("Try Again")
                ),
                secondaryButton: .destructive(
                    Text("Delete")
                )
            )
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

 

 

작동방식은 ActionSheet와 비슷하다. ActionSheet는 Button에 .actionSheet 속성을 추가하였는데 Alert를 사용할 때는 .alert 속성을 사용한다. ActionSheet와의 차이점은 ActionSheet는 버튼을 여러개 만들 수 있지만 Alert는 최대 2개까지만 만들 수 있다.

Alert의 버튼은 ActionSheet와 같이 default, cancel, destructive 총 3가지가 있다.

하지만 버튼을 한개만 사용할 때는 dismissButton 파라미터를 사용하거나 생략을 하고 2가지 버튼을 사용할 때는 primaryButton과 secondaryButton 파라미터를 사용하여 표현해야 한다.

 

Props

— title(String) : Alert의 제목을 입력하는 공간이다.

— message(String) : Alert의 부연 설명을 입력하는 공간이다.

— primaryButton(Alert.Button) : 첫 번째 버튼을 입력하는 공간이다.

— secondaryButton(Alert.Button) : 두번째 버튼을 입력하는 공간이다.

—dismissButton(Alert.Button) : 버튼을 한개만 생성할 때 사용하는 파라미터이다.

 


Popover

Popover도 팝업 뷰 중 하나이다. ActionSheet와 Alert와 다른 점은 뷰가 나오는 방향을 설정할 수 있다.

 

Example1

import SwiftUI

struct ContentView: View {
    @State private var showPopover: Bool = false

        var body: some View {
            VStack {
                Button("Show popover") {
                    self.showPopover = true
                }.popover(
                    isPresented: self.$showPopover,
                    arrowEdge: .bottom
                ) { Text("Popover") }
            }
        }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

 

Button 컴포넌트에서 .popover 속성을 사용하여 나타낼 수 있다. 기본적으로 isPresented 속성이 true일 때 창을 표시하고 arrowEdge를 통해 어디서 팝업뷰가 나올지 결정할 수 있다. 중괄호 안에 팝업 뷰안에 표현하고 싶은 컴포넌트를 넣으면 해당 컴포넌트들이 표시된다.

 

Props

—isPresented(boolean) : true일 때 해당 Popover가 표시된다.

—arrowEdge(enum) : 팝업뷰의 방향을 지정한다.(.top, .bottom, .leading, .trailing)

—content : 해당 뷰에 들어갈 컴포넌트 요소를 입력한다.

 

Example2

import SwiftUI

struct ContentView: View {
    @State var popover: PopoverModel?

        var body: some View {
            VStack(spacing: 150) {
                Button("First Popover", action: {
                    popover = PopoverModel(body: "Custom message #1.")
                })
                .popover(item: $popover) { detail in
                    Text("\(detail.body)")
                }

                Button("Second Popover", action: {
                    popover = PopoverModel(body: "Custom message #2.")
                })
                .popover(item: $popover) { detail in
                    Text("\(detail.body)")
                }
            }
        }
    struct PopoverModel: Identifiable {
            var id: String { body }
            let body: String
        }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

 

Popover 구조체를 생성한 뒤 재사용이 가능하게 만든 예이다. 이때는 item 속성을 사용하여 만들 수 있다. 구조체를 @State로 선언한 뒤 item 속성에 $기호를 사용하면 해당 구조체안에 있는 요소들을 이용하여 Popover 뷰를 만들 수 있다.

반응형

'SwiftUI' 카테고리의 다른 글

SwiftUI Toggle, Label, Grid  (0) 2021.02.22
SwiftUI Gradient  (0) 2021.02.20
SwiftUI Image, Button  (0) 2021.02.17
SwiftUI @State, @Binding, TextField  (0) 2021.02.16
SwiftUI Layout, Text  (0) 2021.02.15