SwiftUI call function on variable change

前端 未结 2 542
后悔当初
后悔当初 2020-12-10 14:10

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

相关标签:
2条回答
  • 2020-12-10 14:24

    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)
                }
            )
        }
    }
    
    0 讨论(0)
  • 2020-12-10 14:37

    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)%")
      }
     }
    }
    
    0 讨论(0)
提交回复
热议问题