GeometryReader is yet another view! Surprised?
In most tutorials I have seen, background is used in its simplest form. For example: Text("hello").background(Color.red). At first glance we may fail to realise that, Color.red, is not just a parameter indicating that the color should be red.
No, Color.red is yet another view!
- SwiftUI로 개인 프로젝트를 진행할 때 GeometryReader를 사용하면 가끔 앱이 크래시되는 일로 인해 원인을 파악하려고 삽질을 했지만 원인을 알 수 없었던 적이 있다. GeometryReader에 대해 자세히 알아보기 위해 읽게 되었다.
SwiftUI has a mechanism that allows us to “attach” some attributes to our views. These attributes are called Preferences, and these may be passed up the view hierarchy easily. There’s even the possibility of installing a callback that executes whenever these preferences change. Have you ever wondered how does NavigationView get the title from .navigationBarTitle(). Note that .navigationBarTitle() does not modify NavigationView directly, instead, it is invoked down the view hierarchy! So how does it do it! Well you probably guessed it already. It uses preferences. In fact, it is mentioned very briefly during the WWDC session SwiftUI Essentials. It is just a 20 second mention, and easily missed. If you’re interested, check Session 216 (SwiftUI Essentials) and jump to 52:35.
When using view preferences, you may use the geometry information from a child, in order to layout one of its ancestors. If that is the case, you should exercise caution. You risk getting stuck in a recursive loop, if the ancestor reacts to changes in the layout of a child, and the child reacts to the changes of the ancestor. You may experience different results. The application may hang, the screen may flicker trying to redraw continuously, and most likely the CPU will spike. All these may be indications that you are using preferences wrong. For example, if you have two views inside a VStack, and the one on the top (A) sets its height, based on the second view (B) y position, you bought yourself a nice little tight loop.
- 위의 아티클을 읽으면서 Recursive하게 읽게 된 아티클.