13

I have 2 simple views:

import SwiftUI

struct ContentView: View {
    @State private var showingModalView = false
    
    var body: some View {
        Button(action: {
            self.showingModalView.toggle()
        }) {
            Text("Show Modal View")
        }.sheet(isPresented: $showingModalView) {
            ModalView()
        }
    }
}

struct ModalView: View {
    var body: some View {
        Text("Modal View")
    }
}

When "Show Modal" button pressed, ModalView is show.

How to change text "Cancel" when ModalView is active to something else?

enter image description here

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Igor R.
  • 399
  • 4
  • 23

1 Answers1

26

This Cancel is actually a navigation bar item. You can replace it with own button using toolbar, like

demo1

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

    var body: some View {
        Button(action: {
            self.showingModalView.toggle()
        }) {
            Text("Show Modal View")
        }.sheet(isPresented: $showingModalView) {
            ModalView()
            .toolbar(content: {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Close") { self.showingModalView = false }
                }
            })

        }
    }
}

also you can hide it at all (and make your custom approach to close, eg. with button in sheet view, etc.)

    }.sheet(isPresented: $showingModalView) {
        ModalView()
        .navigationBarHidden(true)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thanks for sharing this, I am able to replace the Cancel button with Close. But do you know why the Close Button does not respond, and the modal sheet does not dismiss? I find the behavour of modal sheets unpredictable and don't understand why sometimes they work and sometimes not. – alamodey Oct 10 '21 at 22:25
  • I thought this was a SwiftUI bug since watchOS 7. Thanks a lot for this – Sn0wfreeze Oct 26 '21 at 12:44