2

我有一些简单的代码通过调用一个函数(createSampleData)来创建一个数组(newFactoid),然后它作为一个状态保存。视图显示数组的记录 1。到目前为止,一切都很好。但是,我试图在视图中插入一个按钮,该按钮调用一个简单的函数 (refreshFactoid),该函数对数组进行洗牌,理论上会导致视图刷新。问题是当我插入按钮/功能时出现上述错误。如果我删除按钮,错误就会消失。任何指针/帮助表示赞赏。

import SwiftUI

struct ContentView : View {

    @State private var newFactoid = createSampleData()

    var body: some View {

        VStack {

        // Display Category
            Text(newFactoid[1].category).fontWeight(.thin)
            .font(.title)

        // Display Image
        Image("Factoid Image \(newFactoid[1].ref)")
            .resizable()
            .scaledToFit()
            .cornerRadius(15)
            .shadow(color: .gray, radius: 5, x:5, y:5)
            .padding(25)

        // Display Factoid
        Text("A: \(newFactoid[1].fact)")
            .padding(25)
            .multilineTextAlignment(.center)
            .background(Color.white)
            .cornerRadius(15)
            .shadow(color: .gray, radius: 5, x:5, y:5)
            .padding(25)

        // Display Odds
        Text("B: \(newFactoid[1].odds)").fontWeight(.ultraLight)
            .font(.title)
            .padding()
            .frame(width: 150, height: 150)
            .clipShape(Circle())
            .multilineTextAlignment(.center)
            .overlay(Circle().stroke(Color.white, lineWidth: 2))
            .shadow(color: .gray, radius: 5, x: 5, y: 5)

        // Refresh Button
        Button (action: {refreshFactoid()}) {
            Text("Press To Refresh Data")
        }

       // Refresh Function
        func refreshFactoid() {
             newFactoid.shuffle()
             }

        } // End of VStack Closure

    }
}

struct TextUIView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        }
    }
4

2 回答 2

2

func 不能在 VStack 中声明。

在 Button 的操作块中触发随机播放:

Button(action: { self.newFactoid.shuffle() }) {
    Text("Press To Refresh Data")
}

或在 View 结构中声明函数:

struct ContentView: View {

    @State private var newFactoid = createSampleData()

    var body: some View {

        VStack {
            // ...

            // Refresh Button
            Button(action: { self.refreshFactoid() }) {
                Text("Press To Refresh Data")
            }

        } // End of VStack Closure

    }

    // Refresh Function
    func refreshFactoid() {
        newFactoid.shuffle()
    }

}
于 2020-05-18T18:02:28.580 回答
1

只需删除

   // Refresh Function
    func refreshFactoid() {
         newFactoid.shuffle()
         }

    } // End of VStack Closure

来自body

于 2020-05-18T17:12:04.470 回答