SwiftUI:呈现工作表时防止视图刷新 [英] SwiftUI: prevent View from refreshing when presenting a sheet
问题描述
我注意到添加 sheet
修饰符时,SwiftUI完全刷新了视图.
I have noticed that SwiftUI completely refresh view when adding sheet
modifier.
假设我有一个显示随机数的View.我希望该值是独立的,并且不与工作表逻辑相关(每次打开/关闭工作表时都不会更改),但是每个工作表显示/关闭的文本都在更改.
Let's say I have View that displays random number. I expect that this value would be independent and not connected to the sheet logic (not changing every time I open/close sheet), but every time sheet presented/dismissed Text is changing.
是否应该这样工作?我是否错误地认为 @Sate
的要点是仅更新已连接的视图,而不是全部视图?呈现模态时,如何防止View刷新自身?
Is it supposed to work so?
Am I wrong that main point of @Sate
is to update only connected Views but not all stack?
How can I prevent my View from refreshing itself when presenting a modal?
struct ContentView: View {
@State var active = false
var body: some View {
VStack {
Text("Random text: \(Int.random(in: 0...100))")
Button(action: { self.active.toggle() }) {
Text("Show pop up")
}
}
.sheet(isPresented: $active) {
Text("POP UP")
}
}
}
P.S.ContentView仅调用 onAppear()
/ onDisappear()
和 init()
.
P.S. ContentView calls onAppear()
/onDisappear()
and init()
only ones.
推荐答案
它需要制作独立于条件的独立视图以实现您想要的行为,如下所示
It needs to make separated condition-independent view to achieve behavior as you wish, like below
struct RandomView: View {
var body: some View {
Text("Random text: \(Int.random(in: 0...100))")
}
}
struct ContentView: View {
@State var active = false
var body: some View {
VStack {
RandomView()
Button(action: { self.active.toggle() }) {
Text("Show pop up")
}
}
.sheet(isPresented: $active) {
Text("POP UP")
}
}
}
在这种情况下,不会重建 RandomView
,因为它不依赖于 active
状态.
In this case RandomView
is not rebuilt because is not dependent on active
state.
这篇关于SwiftUI:呈现工作表时防止视图刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!