Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
LayoutInSwiftUI.swift
import SwiftUI
import Combine
struct ContentView: View {
var body: some View {
VStack {
Section {
list
.frame(height: 150)
} header: {
Text("List")
}
Section {
grid
.frame(height: 150)
} header: {
Text("Grid")
}
Section {
lazyVGrid
.frame(height: 150)
} header: {
Text("LazyVGrid")
}
Section {
viewThatFits
.frame(height: 150)
} header: {
Text("ViewThatFits")
}
Section {
layout
.frame(height: 150)
} header: {
Text("Layout")
}
}
}
private var viewThatFits: some View {
ViewThatFits {
Text("one")
Text("two")
}
}
private var layout: some View {
BasicView()
}
private var list: some View {
List {
Text("one")
Text("two")
Text("three")
}
}
private var grid: some View {
Grid {
GridRow {
Text("one")
Text("two")
}
GridRow {
Text("three")
Text("four")
Text("five")
}
}
}
private var lazyVGrid: some View {
LazyVGrid(columns: [GridItem(.fixed(50))]) {
Text("one")
Text("two")
Text("three")
Text("four")
}
}
}
struct BasicView: View {
var body: some View {
BasicVStack {
Text("Inside Layout")
}
}
}
struct BasicVStack: Layout {
func placeSubviews(
in bounds: CGRect,
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()
) {
var point = bounds.origin
for subview in subviews {
subview.place(at: point, anchor: .topLeading, proposal: .unspecified)
point.y += subview.dimensions(in: .unspecified).height
}
}
func sizeThatFits(
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()
) -> CGSize {
subviews.reduce(CGSize.zero) { result, subview in
let size = subview.sizeThatFits(.unspecified)
return CGSize(
width: max(result.width, size.width),
height: result.height + size.height)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment