I\'m attempting to create a custom property wrapper supported by SwiftUI, meaning that changes to the corresponding properties values would cause an update to the SwiftUI vi
Ok... here is alternate approach to get similar thing... but as struct only DynamicProperty
wrapped around @State
(to force view refresh).
It is simple wrapper but gives possibility to incapsulate any custom calculations with following view refresh... and as said using value-only types.
Here is demo (tested with Xcode 11.2 / iOS 13.2):
Here is code:
import SwiftUI
@propertyWrapper
struct Refreshing : DynamicProperty {
let storage: State
init(wrappedValue value: Value) {
self.storage = State(initialValue: value)
}
public var wrappedValue: Value {
get { storage.wrappedValue }
nonmutating set { self.process(newValue) }
}
public var projectedValue: Binding {
storage.projectedValue
}
private func process(_ value: Value) {
// do some something here or in background queue
DispatchQueue.main.async {
self.storage.wrappedValue = value
}
}
}
struct TestPropertyWrapper: View {
@Refreshing var counter: Int = 1
var body: some View {
VStack {
Text("Value: \(counter)")
Divider()
Button("Increase") {
self.counter += 1
}
}
}
}
struct TestPropertyWrapper_Previews: PreviewProvider {
static var previews: some View {
TestPropertyWrapper()
}
}