What does the SwiftUI `@State` keyword do?

前端 未结 5 1726
后悔当初
后悔当初 2020-12-08 13:34

The SwiftUI tutorial uses the @State keyword to indicate mutable UI state:

@State var showFavoritesOnly = false

It offers this summ

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 14:04

    Its explained nicely with an example in the WWDC video - Session 204 (starts at 16:00, quotation starts at 20:15)

    One of the special properties of @State variables is that SwiftUI can observe when they're read and written. Because SwiftUI knows that zoomed was read in body, it knows that the view's rendering depends on it. Which means - when a variable changes the framework is going to ask for body again using the new @State value.

    The @State as a Property Wrapper is also elaborated and justified in Data Flow Through Swift UI (5:38) WWDC vid as well. It's shown how it solves the problem when we need a mutable value in an immutable (struct) View.

提交回复
热议问题