将参数传递给 SwiftUI 表 [英] passing parameter to a SwiftUI Sheet
本文介绍了将参数传递给 SwiftUI 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将参数 calledFrom
传递给 SwiftUI 中的工作表.
奇怪的是,该参数在第一次调用时没有使用,但在接下来的调用中有效.
导入 SwiftUI结构内容视图:查看{@State var showSheet = false@State var calledFrom = -1var主体:一些视图{ForEach((1...4), id: \.self) { i in获取按钮(i)}.sheet(isPresented: $showSheet) { Dialog(CalledFrom: calledFrom) }.填充()}func getButton(_ i : Int) ->一些视图{return Button("\(i)"){print("Button \(i)pressed");调用自 = i;showSheet = true }}}结构对话框:查看{var callFrom : Int@Environment(\.presentationMode) 私有变量presentationModevar主体:一些视图{虚拟堆栈{Text("从按钮调用\(callFrom)")按钮(关闭"){presentationMode.wrappedValue.dismiss()}}.填充()}}
解决方案
您必须使用 sheet(item:)
来获得您正在寻找的行为.在 iOS 14 中,sheet
视图是在@State 改变之前计算的:
I need to pass a parameter calledFrom
to a Sheet in SwiftUI.
Strangely, the parameter is not used on the first call, but it works on the following ones.
import SwiftUI
struct ContentView: View {
@State var showSheet = false
@State var calledFrom = -1
var body: some View {
ForEach((1...4), id: \.self) { i in
getButton(i)
}
.sheet(isPresented: $showSheet) { Dialog(calledFrom: calledFrom) }
.padding()
}
func getButton(_ i : Int) -> some View {
return Button("\(i)"){print("Button \(i) pressed"); calledFrom = i; showSheet = true }
}
}
struct Dialog: View {
var calledFrom : Int
@Environment(\.presentationMode) private var presentationMode
var body: some View {
VStack{
Text("Called from Button \(calledFrom)")
Button("close"){presentationMode.wrappedValue.dismiss()}
}
.padding()
}
}
解决方案
You have to use sheet(item:)
to get the behavior you're looking for. In iOS 14, the sheet
view is calculated before the @State changes:
struct ActiveItem : Identifiable {
var calledFrom: Int
var id: Int { return calledFrom }
}
struct ContentView: View {
@State var activeItem : ActiveItem?
var body: some View {
ForEach((1...4), id: \.self) { i in
getButton(i)
}
.sheet(item: $activeItem) { item in
Dialog(calledFrom: item.calledFrom)
}
.padding()
}
func getButton(_ i : Int) -> some View {
return Button("\(i)"){
print("Button \(i) pressed");
activeItem = ActiveItem(calledFrom: i)
}
}
}
这篇关于将参数传递给 SwiftUI 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文