Reputation: 621
How are you doing?
Please consider the following code:
struct ContentView: View {
var body: some View {
NavigationView {
GeometryReader { geometry in
ZStack(alignment: .leading) {
ViewOne()
.frame(height: geometry.size.height / 2)
}
}
}
}
}
struct ViewOne: View {
init() {
print("View one init")
}
var body: some View {
VStack(alignment: .center) {
Text("This is View one")
.font(.system(size: 50))
}
}
}
My question is simple: Why is ViewOne built two times inside a GeometryReader and only once outside of a GeometryReader?
First, I thought that the view needed to be created once, and then a second time taking in consideration the GeometryReader sizes, however, if you have a more complex content within ViewOne, things get messy.
Any ideas??
Thanks for your time and help on this SwiftUI friends!!
Upvotes: 2
Views: 1364
Reputation: 257493
It is not due to GeometryReader
(consider below variant or put in into any xStack), it is because everything in placed into NavigationView
, which makes own complex layout. Moreover you have not rely how many times View.init
is called - View is struct, value, it can be created/copied many times during views layout & rendering (Apple promised to make it optimal, but that's it).
So, just don't put anything heavy (on unrelated) into View.init
(and into View at all). Use for that other design patterns.
struct TestGeometryReaderBuilder: View {
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .leading) {
ViewOne()
.frame(height: geometry.size.height / 2)
}
}
}
}
struct ViewOne: View {
init() {
print("ViewOne> init")
}
var body: some View {
print("ViewOne> build")
return VStack(alignment: .center) {
Text("This is View one")
.font(.system(size: 50))
}
}
}
Upvotes: 3