How to center views with zindex in SwiftUI

Viewed 111

My custom view has two elements, RoundedRectangle and Text. I want these views to be shown as a button. However the views cannot be centered in ZStack.

import SwiftUI

struct CommandButtonView: View {
    let text: String
    let color: Color
    
    var body: some View {
        ZStack(alignment: .center) {
            RoundedRectangle(cornerRadius: 8.0)
                .size(width: 40.0, height: 40.0)
                .fill(color)
                .zIndex(100)
            Text(text)
//                .foregroundColor(.white)
                .font(.system(.body, design: .monospaced))
                .zIndex(101)
        }
    }
}

struct CommandButtonView_Previews: PreviewProvider {
    static var previews: some View {
        CommandButtonView(text: " = ", color: .green)
    }
}

enter image description here

How does alignment of ZStack work?

1 Answers

Here is fixed variant.

demo

struct CommandButtonView: View {
    let text: String
    let color: Color

    var body: some View {
        ZStack(alignment: .center) {
            RoundedRectangle(cornerRadius: 8.0)
                .fill(color)
                .frame(width: 40.0, height: 40.0)
            Text(text)
                .foregroundColor(.white)
                .font(.system(.body, design: .monospaced))
        }
    }
}
Related