繁体   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