📦 GeometryReader
(struct)
SwiftUI ⟩ views ⟩ measuring ⟩ GeometryReader
⭐️ GeometryReader
:
會讀取母視圖的位置尺寸資訊。
會取用母視圖的所有空間。
負責對齊子視圖於左上角❗️ (⭐️) 👉 GeometryReader 的對齊方式
當需要知道某視圖的動態尺寸時,可搭配 .overlay
或 .background
使用,例如:
// view > overlay > GeometryReader
view.overlay { // overlay.frame = view.frame
// ⭐️ GeometryReader 知道 view 的尺寸(透過 `geo.size`)
GeometryReader { geo in
// geo.size :paraent's size
// geo.frame(in: .global):parent's bounds
}
}
💡 註:上面程式碼中,GeometryReader
的母視圖其實是 view.overlay
,不過 view.overlay
的 frame
與 view
的一樣❗️
often used to do custom view layout.
used to solve the problem with .readSize().
used by .getSize() to do something with view's size.
Anchor Preferences Using the subscript, you can get the size and position of any subview down the view tree.
用法:
GeometryReader { geometry in
// geometry.size:size of the paraent
// geometry.frame(in: .global):bounds of the parent
}
A GeometryReader is configured with a ViewBuilder (just like any other container view), but unlike other containers, the view builder for a geometry reader receives a parameter: the GeometryProxy.
The proxy has a property for the view’s proposed layout size and a subscript to resolve anchors.
GeometryReader reports its proposed size back as the actual size. Because of this sizing behavior, geometry readers are often especially useful when used as the background or overlay of another view: they become the exact size of the view. We can use this size either to draw something in the bounds of the view or to measure the size of the view. 👉 Thinking in SwiftUI, p.89, Ch.5, Custom Layout - GeometryReader
CoreGraphics ⟩ CGRect
Last updated
Was this helpful?