Skip to content

Instantly share code, notes, and snippets.

@atrinh0
Last active June 10, 2021 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atrinh0/042ead84f65a71d127dd23897c068f48 to your computer and use it in GitHub Desktop.
Save atrinh0/042ead84f65a71d127dd23897c068f48 to your computer and use it in GitHub Desktop.
SwiftUI Alignment Guides (aligning vertical to horizontal)
import SwiftUI
extension VerticalAlignment {
struct VertAlignName: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
d[.top]
}
}
static let vertAlignName = VerticalAlignment(VertAlignName.self)
}
extension HorizontalAlignment {
struct HorizAlignName: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
d[.top]
}
}
static let horizAlignName = HorizontalAlignment(HorizAlignName.self)
}
struct ContentView: View {
var body: some View {
ZStack(alignment: Alignment(horizontal: .horizAlignName, vertical: .vertAlignName)) {
VStack {
Text("A")
Text("B")
Text("C")
.alignmentGuide(.vertAlignName) { d in d[VerticalAlignment.center] }
.alignmentGuide(.horizAlignName) { d in d[HorizontalAlignment.center] }
}
HStack {
Text("A")
Text("B")
Text("C")
.alignmentGuide(.vertAlignName) { d in d[VerticalAlignment.center] }
.alignmentGuide(.horizAlignName) { d in d[HorizontalAlignment.center] }
}
}
.font(.largeTitle)
}
}
@atrinh0
Copy link
Author

atrinh0 commented May 7, 2021

Screenshot 2021-05-07 at 16 58 54

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment