iosswiftuiswiftui-text

swiftui text is not centered


The code I used below is not center centered. the top space is twice as much as the bottom space. Don't need to be equal to the bottom and top space? How I can center Text?

struct ContentView: View {
    
    var body: some View {
        ZStack(alignment:.center) {
            Color.red
            
            Text("onna")
                .font(.system(size: 60))
        }
        .frame(width: 222, height: 60)
    }
}

enter image description here


Solution

  • Here a way for you to set the value you want:

    struct ContentView: View {
        
        var body: some View {
            
            VStack(spacing: 10.0) {
                
                Text("Onna")
                    .font(.system(size: 60))
                    .baselineOffset(-40.0)
                    .background(Color.red)
                
                Text("Onna")
                    .font(.system(size: 60))
                    .baselineOffset(40.0)
                    .background(Color.blue)
                
            }
    
        }
    }