Skip to content

Instantly share code, notes, and snippets.

@marcprux
Created February 28, 2020 17:57
Show Gist options
  • Save marcprux/1589daadfd57e70c497910b0cc54d15c to your computer and use it in GitHub Desktop.
Save marcprux/1589daadfd57e70c497910b0cc54d15c to your computer and use it in GitHub Desktop.
Example of how to use `alignmentGuide` to align components along two dimensions
//
// ContentView.swift
// AlignDemo
//
// Created by Marc Prud'hommeaux on 2/28/20.
// Copyright © 2020 Glimpse I/O. All rights reserved.
//
import SwiftUI
/*
* Example of how to use `alignmentGuide` to align components along two dimensions.
* This code will make the following layout centered around
* the "XXX" Text view:
*
* O
* OOO -- XXX -------- OOOO
* O
* O
* O
*/
struct ContentView: View {
var body: some View {
HStack {
Text("OOO")
VStack() {
Text("O")
HStack() {
Text("--")
Text("XXX")
.alignmentGuide(.topViewCenter) { d in d[VerticalAlignment.center] }
.alignmentGuide(.leadingViewCenter) { d in d[HorizontalAlignment.center] }
Text("--------")
}
.alignmentGuide(HorizontalAlignment.center) { d in d[.leadingViewCenter] }
Text("O")
Text("O")
Text("O")
}
.alignmentGuide(VerticalAlignment.center) { d in d[.topViewCenter] }
Text("OOOO")
}
}
}
extension VerticalAlignment {
/// The center of the uppermost view in a stack; handy for aligning inspectors sets so the label
/// lines up with the center of the topmost view.
static let topViewCenter = VerticalAlignment(TopViewCenter.self)
private enum TopViewCenter: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat { d[VerticalAlignment.center] }
}
}
extension HorizontalAlignment {
/// The horizontal center of the leadoing view in a stack; handy for aligning the primary inspector control
/// with a label beneath it.
static let leadingViewCenter = HorizontalAlignment(LeadingViewCenter.self)
private enum LeadingViewCenter: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat { d[HorizontalAlignment.center] }
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment