我以前曾尝试将.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)
}
}
答案 0 :(得分:6)
sheet
,actionSheet
和alert
的工作方式是将它们附加到子视图,并决定是否使用条件绑定显示它们。因此,您可以将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)})
}
}
}
答案 1 :(得分:0)
这是第二个示例,只要您希望在视图显示时执行,它就会更加自动化:
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)您只能从视图-类似于Button
或视图的修饰符。
最后,如果您正确设置了模型,则可以 在此处执行功能,设置标记,将视图绑定到模型并基于该标记显示图纸。这可能是首选路线。