Search code examples
swiftswiftuialertarea

Specify an Area in a View — Swift UI


I am creating a game that allow the user to tap on specific area like a green dot. When the user tap on the dot, no reaction is shown. But if the user tap on positions outside the dot, an alert pops up.

Example

I know how alert works, but I don’t know how to specify an area (the green dot) so that I can output an alert.

Thanks for advance if anyone can give me some hints ;p


Solution

  • I haven't tested but why not using a ZStack?

    struct ExampleView: View {
        @State private var showAlert = false
    
        var body: some View {
            ZStack {
                Color.white
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .ignoresSafeArea()
                    .onTapGesture {
                        showAlert.toggle()
                    }
                Circle()
                    .foregroundColor(Color.green)
                    .frame(width: 120, height: 120)
            }
            .alert("Message", isPresented: $showAlert) {
                Button("Ok", role: .cancel, action: { })
            }
        }
    }
    

    Or maybe using the idea of @jnpdx?

    struct OtherExampleView: View {
        @State private var showAlert = false
    
        var body: some View {
            VStack {
                Circle()
                    .foregroundColor(Color.green)
                    .frame(width: 120, height: 120)
                    .background {
                        Color.white
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .ignoresSafeArea()
                            .onTapGesture {
                                showAlert.toggle()
                            }
                    }
            }
            .alert("Message", isPresented: $showAlert) {
                Button("Ok", role: .cancel, action: { })
            }
        }
    }
    

    I'll test these two options tomorrow.