Skip to content

Custom HStack and VStack that allow for a child to be center aligned. Built with SwiftUI.

License

Notifications You must be signed in to change notification settings

atlou/CenteredStack

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CenteredStack

banner

SwiftUI does not allow for a child of an HStack or a VStack to be centered. This package aims to provide a solution to this problem.

Get Started

  1. Add the CenteredStack package to your Xcode project.
  2. Import CenteredStack to your file.
import SwiftUI
import CenteredStack // Here

struct ContentView: View {
    ...
}
  1. Use it like a regular HStack or VStack.
struct ContentView: View {
    var body: some View {
        CenteredVStack {
            // Add content here
        }
    }
}
  1. Add the centered() modifier to the child you want to center.
struct ContentView: View {
    var body: some View {
        CenteredVStack {
            Text("Not centered")
            Text("Centered")
                .centered() // Here
        }
    }
}

Use with Spacer

You cannot use a Spacer and the .centered() modifier in the same stack. If you need to use a Spacer, use a ZStack.

Here is an example:

struct ContentView: View {
    var body: some View {
        ZStack {
            HStack { // Separate HStack that contains the Spacer
                Button("Back") {}
                Spacer()
                Button("Add") {}
            }
            CenteredHStack {
                Image(systemName: "person.fill")
                Text("John Smith")
                    .centered()
            }
        }
        .padding(20)
        .background(.blue.opacity(0.1))
        .clipShape(.rect(cornerRadius: 8))
    }
}

About

Custom HStack and VStack that allow for a child to be center aligned. Built with SwiftUI.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages