我想從按鈕呼叫的 json 檔案創建隨機文本生成器。此時我有隨機文本生成器,但要重繪 我需要回傳另一個視圖并打開相同的視圖。
我怎樣才能讓它通過按鈕重繪 ?我曾嘗試通過函式創建它,但每次我遇到很多錯誤......
ContentView 代碼(除了允許我運行此代碼的黑客 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"
}
]
uj5u.com熱心網友回復:
如您所見,我在author Text. 每次您點擊它時,setRandomQuote都會呼叫它,為您的@Statevar 設定一個隨機參考,隨后將重新加載視圖。
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)
Button(action: setRandomQuote) {
Text("Refresh")
.font(.system(.title3))
.foregroundColor(.white)
.padding()
.background {
RoundedRectangle(cornerRadius: 8)
.foregroundColor(.blue)
}
}
}
}.frame(width: 240)
.background(RoundedRectangle(cornerRadius: 7.0).fill(Color.blue))
}
}.onAppear {
setRandomQuote()
}
}
private func setRandomQuote() {
let quotes = Bundle.main.decode([Quote].self, from: "quotes.json")
quote = quotes.randomElement()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/522577.html
標籤:IOS代码迅捷
上一篇:如何在Swift5中播放聲音
