Is it correct to expect internal updates of a SwiftUI DynamicProperty property wrapper to trigger a view update?

后端 未结 2 922
萌比男神i
萌比男神i 2020-12-10 13:58

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

2条回答
  •  春和景丽
    2020-12-10 14:14

    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):

    DynamicProperty as wrapper on @State

    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()
        }
    }
    

提交回复
热议问题