Skip to content

Instantly share code, notes, and snippets.

@pommdau
Created August 22, 2023 04:33
Show Gist options
  • Save pommdau/f11ae1dd0fe71019d96937d5e9ce324c to your computer and use it in GitHub Desktop.
Save pommdau/f11ae1dd0fe71019d96937d5e9ce324c to your computer and use it in GitHub Desktop.
import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Lorem").horizontalAlignment(.leading)
                .background(.red.opacity(0.1))
            Text("Lorem").horizontalAlignment(.center)
                .background(.green.opacity(0.1))
            Text("Lorem").horizontalAlignment(.trailing)
                .background(.blue.opacity(0.1))
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

// MARK: - View + horizontalAlignment

enum HorizontalAlignment {
    case leading
    case center
    case trailing
}

extension View {
    func horizontalAlignment(_ horizontalAlignment: HorizontalAlignment) -> some View {
        Group {
            if horizontalAlignment == .leading {
                HStack {
                    self
                    Spacer()
                }
            }
            else if horizontalAlignment == .center {
                HStack {
                    Spacer()
                    self
                    Spacer()
                }
            } else if horizontalAlignment == .trailing {
                HStack {
                    Spacer()
                    self
                }
            }
        }
    }
}
@pommdau
Copy link
Author

pommdau commented Aug 22, 2023

image

@pommdau
Copy link
Author

pommdau commented Aug 22, 2023

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