swift - 将参数传递给 SwiftUI 工作表
问题描述
我需要将参数传递给calledFrom
SwiftUI 中的工作表。
奇怪的是,第一次调用时没有使用该参数,但它适用于以下调用。
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()
}
}
解决方案
你必须使用sheet(item:)
来获得你正在寻找的行为。在 iOS 14 中,sheet
视图是在 @State 更改之前计算的:
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)
}
}
}
推荐阅读
- javascript - Background process without influence of Routing in Angular
- python - OpenCV 4 TypeError:参数“标签”的预期 cv::UMat
- node.js - 如何得到猫鼬聚合函数的结果
- javascript - Node app doesn't work after firebase deploy
- android - unable to send image from my application to mvc web api
- python - Using regular expression to divide two words and capture the first word
- python-3.x - Google Cloud Vision API 一次 API 调用中的多个图像注释
- python - 使用切片与范围索引 ndarray 的结果的维度
- webpack - 'ENV' is not recognized as an internal or external command
- android - 如何将 Viewpager 和 recyclerview 放在 BottomSheet 中?