方式一 (使用extension为结构体扩展目标类型)
https://ootips.org/yonat/swiftui-binding-type-conversion/
struct MyView: View {
@State private var currentStep: Double = 0.0
var body: some View {
Slider(value: $currentStep, in: 0.0 ... 9.0, step: 1.0)
ViewWithInt(bindingInt: $currentStep) // Error: 'Binding<Double>' is not convertible to 'Binding<Int>'
}
}
extension Double {
var int: Int {
get { Int(self) }
set { self = Double(newValue) }
}
}
ViewWithInt(bindingInt: $currentStep.int) // Works
方式二 (自定义Binging属性)
https://blog.csdn.net/Forever_wj/article/details/121983620
struct ContentView: View {
@State private var username = ""
var body: some View {
//注意:自定义binding是放在body里面。如果放到成员变量,则会报错:Cannot use instance member 'xxx' within property initializer; property initializers run before 'self' is available
let binding = Binding(
get: { self.username },
set: { self.username = $0 }
)
return VStack {
// 当绑定到自定义 Binding 实例时,不需要在绑定名称前使用 $ 符号,因为已经阅读了双向绑定。
TextField("Enter your name", text: binding)
}
}
}
为了让body看起来简洁,应该把子view封装到成员变量
struct ContentView: View {
@State private var username = ""
var body: some View {
VStack {
myView
otherView...
}
var myView: some view {
let binding = Binding(
get: { self.username },
set: { self.username = $0 }
)
return VStack {
TextField("Enter your name", text: binding)
}
}
}