Layout Containers (佈局容器)

VStack (垂直排列)

VStack(alignment: .leading, spacing: 10) {
    Text("A")
    Text("B")
    Text("C")
}

HStack (水平排列)

HStack(alignment: .center, spacing: 10) {
    Text("A")
    Text("B")
    Text("C")
}

ZStack (疊放)

ZStack(alignment: .leading) {
    Text("ZStack1")
    Text("ZStack2")
}

Lazy Containers (延遲容器)

LazyVStack (垂直排列)

LazyVStack {
    ForEach(0..<100) { Text("Item \($0)") }
}

LazyHStack (水平排列)

LazyHStack {
    ForEach(0..<100) { Text("Item \($0)") }
}

LazyVGrid (垂直格狀佈局)

let columns = [GridItem(.flexible()), GridItem(.flexible())]

LazyVGrid(columns: columns) {
    ForEach(0..<10, id: \.self) { _ in
        Text("LazyVGrid")
    }
}

LazyHGrid (水平格狀佈局)

let rows = [GridItem(.flexible()), GridItem(.flexible())]

LazyHGrid(rows: rows) {
    ForEach(0..<10, id: \.self) { _ in
        Text("LazyHGrid")
    }
}

GeometryReader (幾何讀取器)

GeometryReader { geometry in
    Text("Width: \(geometry.size.width)")
}

Layout Protocol (自訂佈局)

struct MyCustomLayout: Layout {
    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
        return CGSize(width: 100, height: 100)
    }
    
    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
        for subview in subviews {
            subview.place(at: CGPoint(x: bounds.midX, y: bounds.midY), proposal: proposal)
        }
    }
}

MyCustomLayout {
    Text("Custom Layout")
}

索引