The Util Designer
SwiftUI 使用sheet方式來顯示另一個View
xcode 13.4.1, swift 5.5, iOS 15.4
2022-08-17
SwiftUI的sheet是用來在原有的View上而疊加的方式來展示一個新的View,同時又允許用戶可以以下拉的方法來屏除這新的View回到原有的View。
1. 使用sheet,需要一個bool的state變量來控制是否顯示新的View,實作如下:
import SwiftUI

struct DismissView: View {
    
    var body: some View {
        Text("Dismiss View")
    }
}

struct DismissViewExample: View {
    @State private var showingDetail = false

    var body: some View {
        Button {
            showingDetail = true
        } label: {
            Text("Tap me")
        }
        .sheet(isPresented: $showingDetail) {
            DismissView()
        }

    }
}
2. 除了下拉用來屏除這新的View回到原有的View,也可以用一個Environment的方式來實現:
import SwiftUI

struct DismissView: View {
    @Environment(\.dismiss) var dismiss
    var body: some View {
        VStack {
            Text("Detail Content")
            
            Button("Press me to dismiss") {
                dismiss()
            }
            .font(.largeTitle)
            .foregroundColor(.orange)
        }
    }
}

struct DismissViewExample: View {
    @State private var showingDetail = false

    var body: some View {
        Button {
            showingDetail = true
        } label: {
            Text("Tap me")
        }
        .sheet(isPresented: $showingDetail) {
            DismissView()
        }

    }
}