Home > database >  How to align elements on ZStack in SwiftUI?
How to align elements on ZStack in SwiftUI?

Time:02-16

Problem

I am trying to create a view of a card with a symbol in the middle. I tried to achieve this by creating a ZStack. However, despite using .center alignment, the symbol always show in the top left.

Code

In the following code, the contentShape shows on the top-left despite alignment setting.

            ZStack(alignment: .center) {
                let baseShape = RoundedRectangle(cornerRadius: 10)
                let contentShape = Rectangle()
                    .size(width: width, height: height)
                    .foregroundColor(getContentColor(color: card.color))
                
                baseShape.fill().foregroundColor(.white)
                baseShape.strokeBorder(lineWidth: 3, antialiased: true)
                contentShape
            }

ZStack is aligned at top-left corner as such.

Question

How do I properly align the contentShape at the center of the ZStack?

CodePudding user response:

You need to use frame instead of size, because size is just for path drawing within provided rect, but rect here is entire area, so to fix use

demo

ZStack(alignment: .center) {
    let baseShape = RoundedRectangle(cornerRadius: 10)
    let contentShape = Rectangle()
        .frame(width: width, height: height)                  // << here !!
        .foregroundColor(getContentColor(color: card.color))
    
    baseShape.fill().foregroundColor(.white)
    baseShape.strokeBorder(lineWidth: 3, antialiased: true)
    contentShape
}
  • Related