Created
February 28, 2020 17:57
-
-
Save marcprux/1589daadfd57e70c497910b0cc54d15c to your computer and use it in GitHub Desktop.
Example of how to use `alignmentGuide` to align components along two dimensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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