ios – SwiftUI: Why SwiftUI rebuilds a view when an inrelevant property of @Observable information modified

0
26
ios – SwiftUI: Why SwiftUI rebuilds a view when an inrelevant property of @Observable information modified


First, you need to make Web page additionally @Observable. In any other case SwiftUI can not observe its modifications correctly.

@Observable
class Web page {
    var pageTitle = "pageTitle"
    var isAvailable = true
}

Doing this alone just isn’t sufficient to repair the issue, although. To repair this, you may both make a Bindable of the Web page (by which case e book needn’t be @Bindable),

@Bindable var web page = e book.pageOne
Toggle(e book.pageOne.isAvailable ? "web page obtainable" : "web page not obtainable",
       isOn: $web page.isAvailable
)

or do:

Toggle(e book.pageOne.isAvailable ? "web page obtainable" : "web page not obtainable",
       isOn: $e book[dynamicMember: .pageOne.isAvailable]
)

Clarification:

Whenever you do $e book.pageOne.isAvailable, it’s lowered (i.e. equal) to:

$e book[dynamicMember: .pageOne][dynamicMember: .isAvailable]

The primary pair of [] is a name to Bindable.subscript. This creates a Binding. The second pair of [] is a name to Binding.subscript, making a Bindable.

In case you have no thought what that is all about, see SE-0195 and SE-0252.

The issue is that this intermediate Binding. When the ultimate Binding will get modified by the toggle, the setter of isAvailable is clearly known as, however from my observations, the setter of pageOne is additionally known as.

As Web page is a reference sort, this setter name is pointless. Maybe it is because the Binding is produced from the Binding. Bindings are initially designed to work with structs in spite of everything, and if Web page had been a struct, it’s completely essential to name the setter of pageOne.

In any case, as a result of the setter of pageOne is known as, when isAvailable modifications, SwiftUI thinks that pageOne additionally modifications. Since DisplayView.physique calls the getter of pageOne, SwiftUI would name DisplayView.physique once more when isAvailable modifications.

In each options, I eradicated the intermediate Binding, so the setter of pageOne doesn’t get known as.

LEAVE A REPLY

Please enter your comment!
Please enter your name here