Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.0k views
in Technique[技术] by (71.8m points)

ios - Make SwiftUI view grayscale if an alert/sheet is presented

In UIKit and SwiftUI, a sheet or an alert dims standard colors in the view on top of which they were shown. Every color in that view is grayscale during the presentation of an alert/sheet.

How can I dim my SwiftUI view's non-standard colors as well? I'm using my own colors and they do not dim by default.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the .saturation modifier to make your view grayscale when a given alert/sheet is visible.

The following example uses an alert. It utilizes the State variable used for the alert's isPresented parameter in the ternary operator:

.saturation(isAlertVisible ? 0 : 1)

struct ContentView: View {
    @State var isAlertVisible = false

    var body: some View {
        VStack {
            Text("Text")
                .foregroundColor(.red)

            Spacer()
                .frame(height: 300)

            Button {
                isAlertVisible = true
            } label: {
                Text("Button")
            }
            .alert(isPresented: $isAlertVisible) {
                Alert(
                    title: Text("Alert"),
                    message: Text("Message"),
                    dismissButton: Alert.Button.default(Text("OK"))
                )
            }
        }
        .saturation(isAlertVisible ? 0 : 1)
    }
}

Result

GIF of the result

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...