Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I invoke a SwiftUI modal sheet through a function/method?

Tags:

swift

swiftui

I've previously tried appending .sheet on a list and it worked. But for the purpose of my project, I want to invoke a modal alert using a function.

import SwiftUI

struct Battlefield : View {

    @State var isModalInputPresented: Bool = false
    @State var inputTitle: String = ""
    @State var inputMessage: String = ""
    @State var inputValue: Int = 0

    private func summonModalInput(title: String, message: String, input: Int) {
        self.isModalInputPresented.toggle()
        self.inputTitle = title
        self.inputMessage = message
        self.inputValue = input
        sheet(isPresented: $isModalInputPresented, content: { InputView(inputTitle: self.$inputTitle, inputMessage: self.$inputMessage, inputValue: self.$inputValue, isPresented: self.$isModalInputPresented)})
    }

    var body: some View {
        summonModalInput(title: "foo", message: "bar", input: 0)
    }
}
like image 783
ayelvs Avatar asked Mar 13 '26 02:03

ayelvs


1 Answers

The way sheet, actionSheet, and alert work is that you attach them to a child view, and decide whether or not to show them with a conditional binding. So, you can attach the sheet to a child view in this view's body, and give it a conditional binding that you change in the function you want to invoke the modal with.

For example, if you want to present a sheet with a button:

struct Battlefield : View {

    @State var isModalInputPresented: Bool = false
    @State var inputTitle: String = ""
    @State var inputMessage: String = ""
    @State var inputValue: Int = 0

    private func summonModalInput(title: String, message: String, input: Int) {
        self.isModalInputPresented.toggle()
        self.inputTitle = title
        self.inputMessage = message
        self.inputValue = input
        self.isModalInputPresented = true
    }

    var body: some View {
        Button(action: {
            summonModalInput(title: "foo", message: "bar", input: 0)
        }) {
            Text("Tap for an alert!")
        }
        .sheet(isPresented: $isModalInputPresented, 
            content: { 
                InputView(inputTitle: self.$inputTitle, inputMessage: self.$inputMessage, inputValue: self.$inputValue, isPresented: self.$isModalInputPresented)})
        }
    }
}
like image 92
RPatel99 Avatar answered Mar 18 '26 12:03

RPatel99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!