Skip to content

Instantly share code, notes, and snippets.

@jayesh15111988
Created May 9, 2022 21:11
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 jayesh15111988/f39d94a5c2b08c557b6eff9da1cbba1c to your computer and use it in GitHub Desktop.
Save jayesh15111988/f39d94a5c2b08c557b6eff9da1cbba1c to your computer and use it in GitHub Desktop.
A code to add custom alignments to SwiftUI views
import SwiftUI
extension VerticalAlignment {
// A custom vertical alignment to custom align views vertically
private struct TopSectionTitlesAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
// Default to center alignment if no guides are set
context[HorizontalAlignment.center]
}
}
static let topSectionTitlesAlignment = VerticalAlignment(TopSectionTitlesAlignment.self)
}
struct CustomVerticalAlignment: View {
var body: some View {
HStack(alignment: .topSectionTitlesAlignment) {
VStack {
Text("Top Leading Text\nAnother line")
.border(Color.red, width: 1.0)
.padding(.all, 8)
.alignmentGuide(.topSectionTitlesAlignment) {
d in d[VerticalAlignment.center]
}
Text("Bottom Leading")
.border(Color.blue, width: 1.0)
}
.border(Color.yellow, width: 1.0)
Rectangle()
.fill(Color.black)
.frame(height: 1)
.alignmentGuide(.topSectionTitlesAlignment) { d in
d[VerticalAlignment.center]
}
VStack {
Text("Top Trailing Text\nAnother line")
.border(Color.red, width: 1.0)
.padding(.all, 8)
.alignmentGuide(.topSectionTitlesAlignment) { d in
d[VerticalAlignment.center]
}
Text("Bottom Trailing")
.border(Color.blue, width: 1.0)
}
.border(Color.yellow, width: 1.0)
}
.padding()
.border(Color.black, width: 1.0)
}
}
extension HorizontalAlignment {
// A custom horizontal alignment to custom align views horizontally
private struct CustomHorizontalAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
// Default to center alignment if no guides are set
context[VerticalAlignment.center]
}
}
static let customHorizontalAlignment = HorizontalAlignment(CustomHorizontalAlignment.self)
}
struct CustomHorizontalAlignment: View {
var body: some View {
VStack(alignment: .customHorizontalAlignment) {
Text("Top Text Label")
.padding()
.border(Color.red, width: 1.0)
.alignmentGuide(.customHorizontalAlignment) { d in
d[HorizontalAlignment.center]
}
HStack {
Text("Bottom Text Label")
.padding()
.border(Color.orange, width: 1.0)
.alignmentGuide(.customHorizontalAlignment) { d in
d[HorizontalAlignment.center]
}
Image(systemName: "phone")
.border(Color.blue, width: 1.0)
}
}.padding().border(Color.black, width: 1.0)
}
}
struct CustomAlignment_Previews: PreviewProvider {
static var previews: some View {
VStack {
CustomVerticalAlignment()
CustomHorizontalAlignment()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment