【发布时间】:2022-11-14 05:03:59
【问题描述】:
我想从按钮调用的 json 文件创建随机文本生成器。 此时我有随机文本生成器,但要刷新我需要返回另一个视图并打开相同的视图。
我怎样才能让它通过按钮刷新? 我曾尝试通过函数创建它,但每次我遇到很多错误......
ContentView 代码(允许我运行此代码的 hacking swift 代码除外)
struct Quote: Codable {
var text: String
var author: String
var shareMessage: String {
return "\"\(text)\" - \(author)"
}
}
struct PytaniaNormalne : View {
@State private var quote : Quote?
var body: some View {
VStack {
if let quote = quote {
VStack {
VStack {
Text(quote.text)
.font(.system(.title3))
.foregroundColor(.white)
Text(quote.author)
.font(.system(.title3))
.foregroundColor(.white)
}
}.frame(width: 240)
.background(RoundedRectangle(cornerRadius: 7.0).fill(Color.blue))
}
}.onAppear {
let quotes = Bundle.main.decode([Quote].self, from: "quotes.json")
quote = quotes.randomElement()
}
}
}
文件
[
{
"text": "Pytanie 1",
"author": "tekst"
},
{
"text": "Pytanie 2",
"author": "tekst"
},
{
"text": "Pytanie 3",
"author": "teskt"
},
{
"text": "Pytanie 4",
"author": "tekst"
},
{
"text": "Pytanie 5",
"author": "author"
},
{
"text": "Pytanie 6",
"author": "author"
},
{
"text": "Pytanie 7",
"author": "author"
}
]
【问题讨论】:
-
“我曾尝试通过函数创建它,但每次我都会遇到很多错误......”你能展示你的尝试吗?您可能知道如何制作
Button,而在操作中只需要您的两条线let quotes = ...和quote =