coiai Logo

This article is an English translation of the original Japanese post. Read the Japanese original →

[SwiftUI] Adding a "Don't Show Again" Toggle to a Popup

December 19, 2023

Categories: SwiftUI

A toggle where a popup is only shown the first time, and from then on the user can choose whether it appears.

Here's how to implement that.

The popup is shown with .sheet. Just store the "don't show again" flag as a Boolean using AppStorage and you're set.

import SwiftUI

struct ContentView: View {
    @AppStorage("dontShowAgain") var dontShowAgain = false
    @State private var showingPopup = false

    var body: some View {
        VStack {
            Button("Show Popup") {
                if !dontShowAgain {
                    showingPopup = true
                }
            }
        }
        .sheet(isPresented: $showingPopup) {
            HowToSetIcon(dontShowAgain: $dontShowAgain)
        }
    }
}

And here's what's inside popupView

import SwiftUI

struct PopupView: View {
    @Environment(\.presentationMode) var presentationMode
    @Binding var dontShowAgain: Bool

    var body: some View {
        VStack {
            Text("This is a popup")

            Toggle(isOn: $dontShowAgain) {
                Text("二度と表示しない")
            }

            Button("Close") {
                self.presentationMode.wrappedValue.dismiss()
            }
        }
    }
}
[SwiftUI] Adding a "Don't Show Again" Toggle to a Popup | coiai Inc.