gpt4 book ai didi

SwiftUI 保存新对象并导航到它

转载 作者:行者123 更新时间:2023-12-04 03:33:20 25 4
gpt4 key购买 nike

当按下 NavigationLink 时,我想创建一个对象(带有按下时间),将其添加到 savedObjects 中,然后将新对象传递到目标 View 。在 View 更新时如何在不更改状态的情况下执行此操作?

struct ContentView: View {

@State private var savedObjects = [
MyObject(
id: 0,
date: Date()
),
MyObject(
id: 1,
date: Date()
),
MyObject(
id: 2,
date: Date()
),
MyObject(
id: 3,
date: Date()
)
]

var body: some View {
NavigationView {
List {
NavigationLink("Save new object and navigate to it", destination: DestinationView(object: MyObject(id: Int.random(in: 10...1000), date: Date())))
ForEach(savedObjects) { object in
NavigationLink("Navigate to object \(object.id)", destination: DestinationView(object: object))
}
}
}
}
}

class MyObject: ObservableObject, Identifiable {
var id: Int
var date: Date

init(id: Int, date: Date) {
self.id = id
self.date = date
}
}

struct DestinationView: View {

@ObservedObject var object: MyObject

var body: some View {
VStack {
Text("object \(object.id)")
Text("date: \(object.date.description)")
}
}
}

最佳答案

这是一个在链接出现时使用新日期刷新状态的解决方案。

struct LinkWithPayloadView: View {
@State private var date = Date()

var body: some View {
NavigationView {
navigationLink(payload: "Cookies and Milk", date: date)
.onAppear(perform: {
date = Date()
})
}
}

func navigationLink(payload: String, date: Date) -> some View {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
let payload = Payload(timestamp: date, inners: payload)

let vstack = VStack {
Text("\(payload.inners)")
Text("\(formatter.string(from: payload.timestamp))")
}

return NavigationLink(payload.inners, destination: vstack)
}

struct Payload {
let timestamp : Date
let inners : String
}
}

Credit @mallow for the idea

关于SwiftUI 保存新对象并导航到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67462686/

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