Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//
// ContentView.swift
// Layout
//
// Created by Matt Gallagher on 7/6/19.
// Copyright © 2019 Matt Gallagher. All rights reserved.
//
import SwiftUI
struct RowFrames: PreferenceKey {
static var defaultValue: [Anchor<CGRect>] { return [] }
static func reduce(value: inout [Anchor<CGRect>], nextValue: () -> [Anchor<CGRect>]) {
value.append(contentsOf: nextValue())
}
}
struct Row: View {
let text: Text
var body: some View {
text.color(.white).padding().anchorPreference(key: RowFrames.self, value: .bounds) { [$0] }
}
}
struct LeftColumn: View {
var body: some View {
VStack {
Text("Shrink to fit column").fontWeight(.heavy)
Row(text: Text("I'd really like these"))
Row(text: Text("Blue"))
Row(text: Text("Backgrounds"))
Row(text: Text("To fill"))
Row(text: Text("The width of this column"))
Spacer()
}.backgroundPreferenceValue(RowFrames.self) { value in
GeometryReader { geometry in
ZStack {
ForEach(0..<value.count) { i in
RoundedRectangle(cornerRadius: 8)
.fill(Color.blue)
.offset(x: 0, y: geometry[value[i]].origin.y)
.frame(width: geometry.size.width, height: geometry[value[i]].size.height)
.fixedSize()
}
}
}
}.padding().background(Color(appearanceName: .quaternaryLabel))
}
}
struct ContentView : View {
var body: some View {
HStack(spacing: 0) {
LeftColumn()
GeometryReader { geometry in
ScrollView {
VStack(alignment: .leading, spacing: 8) {
Text("A description of the problem").fontWeight(.heavy)
Text("""
Finally made a vertical-only scroll view. This area is \
fixed to the width of the containing scroll view.
The VStack column on the left of this ContentView is sized \
to fit the widest text label plus padding, but no larger \
(shrink to fit). This layout is tricky in SwiftUI but I \
think there's a better approach than I'm using. Still it \
reveals a few tricks that you can use in SwiftUI.
"""
).lineLimit(nil)
Spacer()
}.padding().frame(maxWidth: geometry.size.width, minHeight: geometry.size.height)
}
}
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.