SwiftUI状态初始化器之间的区别

时间:2019-10-20 14:39:51

标签: swift swiftui

初始化urlAnalyzer()变量时,有两个初始化程序:

@State

两个初始值设定项之间是否有所不同? 创建新的/// Initialize with the provided initial value. public init(wrappedValue value: Value) /// Initialize with the provided initial value. public init(initialValue value: Value) 变量时是否首选其中之一?

2 个答案:

答案 0 :(得分:0)

根据swift-evolution proposal

  

@State已重命名为init(initialValue:)以匹配属性名称。

从Swift 5.1开始,两者均可用,并且都未标记为不推荐使用。我仍然建议使用init(wrappedValue:)

答案 1 :(得分:0)

您不直接调用此初始值设定项(init(wrappedValue :))。而是使用@State属性声明一个属性,并提供一个初始值。例如,@ State private var isPlaying:Bool = false。

仅供参考:https://developer.apple.com/documentation/swiftui/state/3365450-init

我们使用init(initialValue :)创建具有初始值的状态。

例如:

struct TestView3: View {
    @ObservedObject var data = TestData.shared
    @State private var sheetShowing = false
    var body: some View {
        print("test view3 body, glabel selected = \(data.selected)"); return
        VStack {
            Text("Global").foregroundColor(data.selected ? .red : .gray).onTapGesture {
                self.data.selected.toggle()
            }.padding()
            Button(action: {
                self.sheetShowing = true
                print("test view3, will show test view4")
            }) { Text("Show TestView4") }.padding()
        }.sheet(isPresented: $sheetShowing) { TestView4(selected: self.data.selected) }
    }
}

struct TestView4: View {
    @ObservedObject var data = TestData.shared
    @State private var selected = false
    init(selected: Bool) {
        self._selected = State(initialValue: selected)   // <-------- here
        print("test view4 init, glabel selected = \(data.selected), local selected = \(self.selected)")
    }
    var body: some View {
        print("test view4 body, glabel selected = \(data.selected), local selected = \(selected)"); return
        VStack {
            Text("Local").foregroundColor(selected ? .red : .gray).onTapGesture {
                self.selected.toggle()
                print("test view4, local toggle")
            }.padding()
            Text("Global").foregroundColor(data.selected ? .red : .gray).onTapGesture {
                self.data.selected.toggle()
                print("test view4, global toggle")
            }.padding()
        }
    }
}