我们经常会使用Binding来把一个打通两个View。最常见的一个例子就是Picker:
自定义Binding
使用Binding实例
如果我们在Picker选择发生变化时想做一些操作,就会发现问题了,因为Picker里不好写.onTapGesture。这时就需要使用自定义Binding变量了。最简单的方法,就是在selection参数处直接定义一个Binding,就像这段代码,一个Binding的实例有了get和set两个匿名函数,你可以完成自己的自定义操作了(联动改变choosed的值)。
import SwiftUI
struct MyContentView : View {
@State private var choosed = "You selected 1"
@State var choosed_int = 1
var body: some View{
VStack{
Text("\(choosed)")
Picker("Please Choose",
selection: Binding(
get: { choosed_int },
set: {
choosed_int = $0
choosed = "You select \($0)"
})) {
Text("hello 1").tag(1)
Text("hello 2").tag(2)
Text("hello 3").tag(3)
}.frame(width: 100)
}
}
}
使用body内的Binding实例
对于在Picker声明时写大段的代码,这确实从代码的可读性上显得不够优雅。所以我们可以在body里声明一个Binding的实例来优雅的完成这段代码:
import SwiftUI
struct MyContentView : View {
@State private var choosed = "You selected 1"
@State var choosed_int = 1
var body: some View{
let binding = Binding(
get: { choosed_int },
set: {
choosed_int = $0
choosed = "You select \($0)"
})
return VStack{
Text("\(choosed)")
Picker("Please Choose",
selection: binding ) {
Text("hello 1").tag(1)
Text("hello 2").tag(2)
Text("hello 3").tag(3)
}.frame(width: 100)
}
}
}
对View的Binding属性进行自定义
如果对一个已经使用Binding声明的属性,想做自定义的getter和setter也是一个非常方便的事:
struct MyContentView : View {
@State private var choosed = "You selected 1"
@Binding var value:Int
var choosed_int : Binding<Int>{
Binding<Int>(
get: {
return self.value
},
set: {
self.value = $0
choosed = "You select \($0)"
}
)
}
var body: some View{
VStack{
Text("\(choosed)")
Picker("Please Choose",
selection: choosed_int ) {
Text("hello 1").tag(1)
Text("hello 2").tag(2)
Text("hello 3").tag(3)
}.frame(width: 100)
}
}
}