2

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?

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.