簡體   English   中英

如何通過函數/方法調用SwiftUI模態表?

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

我以前嘗試過將.sheet附加在列表上,並且可以正常工作。 但是出於我的項目目的,我想使用一個函數來調用模式警報。

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)
    }
}

工作sheetactionSheetalert工作的方式是將它們附加到子視圖,並決定是否使用條件綁定顯示它們。 因此,您可以將工作sheet附加到該視圖主體中的子視圖,並為其提供條件綁定,以便您在要使用其調用模式的函數中進行更改。

例如,如果要顯示帶有按鈕的工作表:

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)})
        }
    }
}

這是第二個示例,只要您希望在視圖出現時執行,它就會更加自動化:

var body: some View {
    ...
}
.onAppear { self.summonModalInput(title: "foo", message: "bar", input: 0) }
.alert(isPresented: $isModalInputPresented { InputView(inputTitle: self.$inputTitle, inputMessage: self.$inputMessage, inputValue: self.$inputValue, isPresented: self.$isModalInputPresented)}

我喜歡@ RPatel99給出的答案,但是這個-如果它滿足您的需求-也會起作用。

要記住的事情是(a)SwiftUI更加是一個“反應式”平台,(b)您的View 需要輸出,並且(c)您只能執行View的功能-例如對Button或View的修改器。

最后,如果您正確設置了模型,則可以在此處執行功能,設置標記,將視圖綁定到模型並基於該標記顯示圖紙。 這可能是首選路線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM