任何想法为何在所有存储的属性初始化之前都会给“自我”使用错误
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])
}
答案 0 :(得分:1)
因为@State
并不意味着从更高的Views
继承。 "You should only access a state property from inside the view’s body"。使用@Binding
which can receive from an @State
from 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"]))
}
}