SwiftUI错误-Type()无法确认查看:只有struct / enum / class类型可以符合协议

我有一些简单的代码,可以通过调用一个函数(createSampleData)来创建数组(newFactoid),然后将其保存为State。视图显示阵列的记录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,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,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()
        }
    }
wwz1989 回答:SwiftUI错误-Type()无法确认查看:只有struct / enum / class类型可以符合协议

只需删除

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

    } // End of VStack Closure

来自body

,

不能在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()
    }

}
本文链接:https://www.f2er.com/2326387.html

大家都在问