SwifUI view life cycle

SwifUI view life cycle

SwifUI view life cycle

Each view faces series of different events from start to end, that is known as lifecycle. It is very important to understand lifecycle when we build app.

Each and every view in SwiftUI has its lifecycle that can be analysed in its three main phases. The three phases that a view observe are Appearing, Updating and Disappearing.

There are also two rendering phases of view i.e Layout and Commit.

Layout phase the non-rendering view hierarchy, computes frames, connects views to state, calculates diffs to be committed onscreen.

Commit phase updates the rendering view hierarchy, commits all changes onscreen, and destroys all views which are not needed anymore.

Appearing

Inserting view into a view graph is known as Appearing. In this, view is first initialised, then subscribed to state, and then rendered for first time.

  • During initialisation, view is not connected with the state. That make its construction weak since the whole view hierarchy is built upfront.
  • After initialisation, and before body computed, a view got connected to the state.
  • body of the view is called for the first time.
  • Render changes and Update the view graph.
  • The onAppear() method is called top-down: from parent to child view.

Updating

External event or state mutation is performed in updating. It means combines publisher which is a single abstraction to remarksent external changes to SwiftUI.

  • SwiftUI detects data emitted by a publisher observed via View.onReceive().
  • View which receive external event or owns mutated sate is compared with previous snapshot. At that point, we provide custom definition of view equality by conforming view with Equatable protocol and wrapping it with EquatableView.
  • SwiftUI invalidates the views that have changed.
  • Update view graph and render invalidated views. All the updates flow down through the view hierarchy.

Disappearing

Removing view view from its hierarchy is called Disappearing.

onDisappear() method is called after view removed from hierarchy. Same on Appear(), onDisapper() method is called from top to down from parent to child view.

I Hope you enjoy this blog

Thank You

Want a Team that Delivers Result ? Connect now with us.

Our Offices

INDIA

F-429, Phase 8B, Industrial Area, SAS Nagar, Punjab 160059

+91 82198-18163

USA

13506 Summerport Village Pky Suite 355 Windermere, FL 34786

+1 (321) 900-0079

CANADA

15 Meltwater Cres, Brampton L6P3V8

+1 (647) 892-6147