如何传递绑定属性的初始值

  • 本文关键字:属性 何传递 绑定 swiftui
  • 更新时间 :
  • 英文 :


我有这个代码:

struct MyView: View {
@State var fieldValue = 0
init(fieldValue:Int) {
self.fieldValue = fieldValue
}
var numberProxy: Binding<String> {
Binding<String>(
get: {
String(fieldValue)
},
set: {
fieldValue = Int($0) ?? 0
}
)
}
var body: some View {
TextField("", text: numberProxy,
onEditingChanged: { status in
},
onCommit:{

})
}

我从另一个角度称之为:

MyView(200)

但是MyView总是显示0

如何使传递的值显示什么是绑定属性?

这个init基本上是一条死胡同,但它似乎正是您对的要求

struct MyViewParent: View {
var body: some View {
VStack{
//You will never receive anything back with this init
MyView(200)
}
}
}
struct MyView: View {
//State is a source of truth it will never relay something to a previous View
@State var fieldValue: Int //= 0 //Another init - Apple recommended
///Not a good way to init
init(_ fieldValue:Int) {
//You can init State here but there is no connection with the previous View
//This is not recommended per Apple documentation State should only accessed from a View body
//https://developer.apple.com/documentation/swiftui/state
self._fieldValue = State(initialValue: fieldValue)
}

//Binding is a 2-way connection
//https://developer.apple.com/documentation/swiftui/binding
var numberProxy: Binding<String> {
Binding<String>(
get: {
String(fieldValue)
},
set: {
fieldValue = Int($0) ?? 0
}
)
}

var body: some View {
VStack{
//Shows that your proxy updates the State
//Resets if a letter is put into the textfield.
Text(fieldValue.description)
TextField("", text: numberProxy, onEditingChanged: { status in  }, onCommit:{ })
}
}
}

使用此init,您可以获得更改

struct MyViewParent: View {
@State var value: Int = 0
var body: some View {
VStack{
//Receives the changes from MyView
Text(value.description)
MyView(fieldValue: $value)
}
}
}
struct MyView: View {
//Binding is a 2-way connection
@Binding var fieldValue: Int 
//Binding is a 2-way connection
//https://developer.apple.com/documentation/swiftui/binding
var numberProxy: Binding<String> {
Binding<String>(
get: {
String(fieldValue)
},
set: {
fieldValue = Int($0) ?? 0
}
)
}

var body: some View {
VStack{
//Shows that your proxy updates this View's Binding and parent State
//Resets to 0if a letter is put into the textfield.
Text(fieldValue.description)
TextField("", text: numberProxy, onEditingChanged: { status in  }, onCommit:{ })
}
}
}

使用State(initialValue:)

struct MyViewTest55: View {

@State private var fieldValue = 0

init(fieldValue: Int) {
self._fieldValue = State(initialValue: fieldValue)
}

var numberProxy: Binding<String> {
Binding<String>(
get: {
String(fieldValue)
},
set: {
fieldValue = Int($0) ?? 0
}
)
}

var body: some View {
TextField("", text: numberProxy,
onEditingChanged: { status in

},
onCommit:{

})
}
}

最新更新