I am trying to convert a view of my watchOS App to Swift UI. I wanted to port the volume control that can be found in watchKit to SwiftUI with custom controls. In the image
You can use a custom Binding
, that calls some code in set
. For example from :
extension Binding {
/// Execute block when value is changed.
///
/// Example:
///
/// Slider(value: $amount.didSet { print($0) }, in: 0...10)
func didSet(execute: @escaping (Value) ->Void) -> Binding {
return Binding(
get: {
return self.wrappedValue
},
set: {
self.wrappedValue = $0
execute($0)
}
)
}
}
As you said "In the past I would have done this with a didSet, but this is no longer available" I test below code it works perfectly
struct pHome: View {
@State var prog:Int = 2 {
willSet{
print("willSet: newValue =\(newValue) oldValue =\(prog)")
}
didSet{
print("didSet: oldValue=\(oldValue) newValue=\(prog)")
//Write code, function do what ever you want todo
}
}
var body: some View {
VStack{
Button("Update"){
self.prog += 1
}
Text("\(self.prog)%")
}
}
}