Skip to content

Instantly share code, notes, and snippets.

@onmyway133
Created June 8, 2022 09:34
Show Gist options
  • Save onmyway133/fc08111964984ef544a176a6e9806c18 to your computer and use it in GitHub Desktop.
Save onmyway133/fc08111964984ef544a176a6e9806c18 to your computer and use it in GitHub Desktop.
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