所有存储的属性初始化之前使用“ self”错误SwiftUI

时间:2020-10-18 12:47:56

标签: swiftui state

任何想法为何在所有存储的属性初始化之前都会给“自我”使用错误

struct ContentView: View {
   @State private var activities : [ActivityModel]
   @State private var currentAcitivity : ActivityModel
   init() {
      let tmpActivities : [ActivityModel] = [ActivityModel(name: "@Home", notes: "At Home", schedule: nil)
      ,ActivityModel(name: "@Work", notes: "At Work", schedule: nil)]

      _activities = State<[ActivityModel]>(wrappedValue:  tmpActivities)
      _currentAcitivity = State<ActivityModel>(wrappedValue: tmpActivities[0])
      
   }

1 个答案:

答案 0 :(得分:1)

因为@State并不意味着从更高的Views继承。 "You should only access a state property from inside the view’s body"。使用@Binding which can receive from an @Statefrom a parent View@EnvironmentObject之类的替代项,它们从@ObservedObject

接收
import SwiftUI

struct StateDemo: View {
    @Binding var array: [String]
    
    init(higherViewArray: Binding<[String]>){
        self._array = higherViewArray
    }
    var body: some View {
        VStack{
            Text("list")
            ForEach(array, id: \.self){ txt in
                Text(txt)
            }
        }
    }
}

struct StateDemo_Previews: PreviewProvider {
    static var previews: some View {
        StateDemo(higherViewArray: .constant( ["0", "1", "2"]))
    }
}