gpt4 book ai didi

swift - 将参数传递给 SwiftUI 工作表

转载 作者:行者123 更新时间:2023-12-05 00:53:56 28 4
gpt4 key购买 nike

我需要将参数 callFrom 传递给 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 View 在 @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)
}
}
}

关于swift - 将参数传递给 SwiftUI 工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66936406/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com