【发布时间】:2021-03-05 23:27:28
【问题描述】:
我希望能够将对象列表存储在单独的 Swift 文件中,并在页面中调用它们以显示它们。我用这段代码成功地做到了:
import Foundation
import SwiftUI
struct MatchInfo: Hashable, Codable {
let theType: String
let theWinner: String
let theTime: String
let id = UUID()
}
var matchInfo = [
MatchInfo(theType: "Capitalism", theWinner: "Julia", theTime: "3/3/2021"),
MatchInfo(theType: "Socialism", theWinner: "Julia", theTime: "3/2/2021"),
MatchInfo(theType: "Authoritarianism", theWinner: "Luke", theTime: "3/1/2021")
]
我在此处的另一个页面上播放比赛后附加到列表的位置:
matchInfo.insert(MatchInfo(theType: typeSelection, theWinner: winnerName, theTime: "\(datetimeWithoutYear)" + "\(year)"), at: 0)
这是另一个页面上的一些代码,我将其称为列表:
List {
ForEach(matchInfo, id: \.self) { matchData in
matchRow(matchData : matchData)
} .background(Color("invisble"))
.listRowBackground(Color("invisble"))
} .frame(height: 490)
...
struct matchRow: View {
let matchData: MatchInfo
var body: some View {
HStack {
VStack(alignment: .leading) {
Text(matchData.theType)
.font(.system(size: 20, weight: .medium, design: .default))
Text(" Winner: " + matchData.theWinner)
}
Spacer()
Text(matchData.theTime)
.padding(.leading, 40)
.multilineTextAlignment(.trailing)
}
.foregroundColor(.white)
.accentColor(.white)
}
}
但此代码不会通过应用重新启动保存。我以前从未通过重新启动保存过任何东西,并且一直在努力寻找一个足够简单让我理解的答案。如何在下次打开应用时更新列表而不使其消失?
【问题讨论】:
标签: swiftui swift5 swiftui-list