SwiftUI的一個神奇之處在于,我們在做某些功能的時候,無需過多地關(guān)心布局信息,而是把主要精力放在業(yè)務(wù)邏輯部分,后續(xù)的文章中,我會專門寫一篇Data Flow的文章。
那么SwiftUI布局的核心原理是什么呢? 主要分3個步驟:
- 父view提供一個建議的size
- 子view根據(jù)自身的特性返回一個size
- 父view使用子view返回的size對子view進(jìn)行布局
舉個例子??:

struct Example3: View {
var body: some View {
HStack(spacing: 0) {
Text("舉個例子??")
MyRectangle()
}
.frame(width: 200, height: 100, alignment: .center)
.border(Color.green, width: 1)
}
struct MyRectangle: View {
var body: some View {
Rectangle().fill(Color.green)
}
}
}
在上邊的圖片中,可以看出,HStack作為父view,他的尺寸是200*100,Text的寬度依賴文字的寬度,而剩余的寬度就都給了MyRectangle。
大家只需要仔細(xì)思考SwiftUI布局的3個步驟,再對照代碼和運(yùn)行效果,就能明白其中道理。我們不在這里做更多解釋。那么這跟GeometryReader有什么關(guān)系呢?
GeometryReader的主要作用就是能夠獲取到父view建議的尺寸。
我們稍微修改一下上邊的代碼:
struct ContentView: View {
var body: some View {
Example4()
.frame(width: 200, height: 100, alignment: .center)
}
}
struct Example4: View {
var body: some View {
GeometryReader { proxy in
HStack(spacing: 0) {
Text("舉個例子??, \(proxy.size.width)")
// .layoutPriority(1)
MyRectangle()
}
.border(Color.green, width: 1)
}
}
struct MyRectangle: View {
var body: some View {
Rectangle().fill(Color.green)
}
}
}

可以看到,確實獲取到了父view的width,但是為什么文字自動換行了呢?是因為在HStack中,Text和MyRectangle擁有同樣的布局優(yōu)先級,要想讓文字盡可能的展示完整,只需提升Text的布局優(yōu)先級即可。
.layoutPriority(1)
GeometryProxy
在上邊例子中,我們用到了一個proxy參數(shù),這個參數(shù)的類型是GeometryProxy,我們先看看它的定義:
public struct GeometryProxy {
public var size: CGSize { get }
public subscript<T>(anchor: Anchor<T>) -> T { get }
public var safeAreaInsets: EdgeInsets { get }
public func frame(in coordinateSpace: CoordinateSpace) -> CGRect
}
- size比較直觀,就是返回父view建議的尺寸
- subscript可以讓我們獲取.leading,.top等等類似這樣的數(shù)據(jù)
- safeAreaInsets可以獲取安全區(qū)域的Insets
- frame(in:)要求傳入一個CoordinateSpace類型的參數(shù),也就是坐標(biāo)空間,可以是.local, .global 或者 .named(),其中 .named()可以自定義坐標(biāo)空間,這個在下邊的例子中會用到
接下來,我們會演示兩個例子來進(jìn)一步學(xué)習(xí)GeometryReader。
RoundedCornersView

struct RoundedCornersView: View {
var color: Color = .black
var topLeading: CGFloat = 0.0
var topTrailing: CGFloat = 0.0
var bottomLeading: CGFloat = 0.0
var bottomTrailing: CGFloat = 0.0
var body: some View {
GeometryReader { geometry in
Path { path in
let w = geometry.size.width
let h = geometry.size.height
let tr = min(min(self.topTrailing, h/2), w/2)
let tl = min(min(self.topLeading, h/2), w/2)
let bl = min(min(self.bottomLeading, h/2), w/2)
let br = min(min(self.bottomTrailing, h/2), w/2)
path.move(to: CGPoint(x: w / 2.0, y: 0))
path.addLine(to: CGPoint(x: w - tr, y: 0))
path.addArc(center: CGPoint(x: w - tr, y: tr), radius: tr, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false)
path.addLine(to: CGPoint(x: w, y: h - br))
path.addArc(center: CGPoint(x: w - br, y: h - br), radius: br, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 90), clockwise: false)
path.addLine(to: CGPoint(x: bl, y: h))
path.addArc(center: CGPoint(x: bl, y: h - bl), radius: bl, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 180), clockwise: false)
path.addLine(to: CGPoint(x: 0, y: tl))
path.addArc(center: CGPoint(x: tl, y: tl), radius: tl, startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 270), clockwise: false)
}
.fill(self.color)
}
}
}
像下邊這樣使用:
Text("大圣,")
.font(.title2)
.padding(.all, 10)
.background(RoundedCornersView(color: .green,
topLeading: 0,
topTrailing: 30,
bottomLeading: 30,
bottomTrailing: 0))
從上邊的代碼和效果圖來看,通過GeometryProxy,我們可以獲取到父view建議的尺寸,在本例中,RoundedCornersView的父view其實是background??梢栽谶@里下載封裝好的代碼SwiftUI-RoundedCornersView。
滾動試圖

正如上圖所示,隨著滾動的距離,動態(tài)計算圖片翻轉(zhuǎn)的角度。為實現(xiàn)這一功能,需要用到一點(diǎn)點(diǎn)數(shù)學(xué)知識:
- 定義屏幕中間位置的圖片旋轉(zhuǎn)角度為0
- 根據(jù)view當(dāng)前的center相當(dāng)于屏幕的位置求出percent
- 應(yīng)用3D旋轉(zhuǎn),沿y軸
代碼比較簡單,在這里就不做更多解釋了,代碼如下:
struct Example2: View {
let img = ["1", "2", "3", "4", "5"]
var body: some View {
ScrollView(.horizontal) {
LazyHStack(spacing: 0) {
ForEach(0..<img.count) { index in
GeometryReader { proxy in
Image(img[index])
.resizable()
.aspectRatio(contentMode: .fill)
.rotation3DEffect(self.rotateAngle(proxy), axis: (x: 0, y: 11, z: 0))
}
.frame(width: 600.0 / 3, height: 600.0 / 3 * (425 / 640))
}
}
}
.frame(width: 600)
.coordinateSpace(name: "ScrollViewSpace")
}
func rotateAngle(_ proxy: GeometryProxy) -> Angle {
let dif = 600 * 0.5 - proxy.frame(in: .named("ScrollViewSpace")).midX
let pct = min(dif / proxy.size.width * 0.5, 1)
return .degrees(Double(30 * pct))
}
}
我們可以通過.coordinateSpace(name: "ScrollViewSpace")這種方式給某個View自定義一個坐標(biāo)空間,然后通過proxy.frame(in: .named("ScrollViewSpace")).midX來獲取到某個view當(dāng)前的位置在指定坐標(biāo)空間中的坐標(biāo)。
也就是說,我們需要獲取Image在其父viewScrollView中的相對坐標(biāo)。
總結(jié)
GeometryReader讓我們能夠獲取到父view提供的建議的size,該數(shù)據(jù)保存在GeometryProxy,GeometryProxy提供了一個frame(in:)函數(shù),可以讓我們分別獲取到該view相對于.global、.local或者.name的size。
查看本文示例代碼:GeometryDemo.swift
SwiftUI集合:FuckingSwiftUI