SwiftUI how to prevent view to reload whole body

后端 未结 1 1719
悲&欢浪女
悲&欢浪女 2021-02-06 05:03

Basically I try to figure out when my viewModel get updated, it will notify view and it will refresh whole body. How to avoid that. For example if my view GoLiveView already pre

相关标签:
1条回答
  • 2021-02-06 05:34

    SwfitUI has a pattern for this. It needs to conform custom view to Equatable protocol

    struct CustomView: View, Equatable {
    
        static func == (lhs: CustomView, rhs: CustomView) -> Bool {
            // << return yes on view properties which identifies that the
            // view is equal and should not be refreshed (ie. `body` is not rebuilt)
        }
    ...
    

    and in place of construction add modifier .equatable(), like

    var body: some View {
          CustomView().equatable()
    }
    

    yes, new value of CustomView will be constructed every time as superview refreshing (so don't make init heavy), but body will be called only if newly constructed view is not equal of previously constructed

    Finally, it is seen that it is very useful to break UI hierarchy to many views, it would allow to optimise refresh a lot (but not only good design, maintainability, reusability, etc. :^) ).

    0 讨论(0)
提交回复
热议问题