SwiftUI call function on variable change

前端 未结 2 548
后悔当初
后悔当初 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)
                }
            )
        }
    }
    

提交回复
热议问题