Search code examples
textalignmentswiftui

SwiftUI - how to align text relative to text below


In the image below I have a first and last name. I would like the last name to be centered, as shown by the middle blue line, while the first name is left-aligned with the last name, as shown by the first blue line. I'm using a GeometryReader to set the vertical position based on a percentage of the overall height, but I have no idea how to get the lower text position and pass it to the upper one.

struct NameText: View {
    var body: some View {
        GeometryReader { geo in
            VStack {
                Text("PETER")
                    .fontWeight(.bold)
                    .font(.title)
                    .foregroundColor(Color(red: 30/255, green: 82/255, blue: 132/255, opacity: 1.0))
                    .offset(x: 0, y: geo.size.height * -0.75)
                Text("PARKER")
                    .fontWeight(.thin)
                    .font(.largeTitle)
                    .offset(x: 0, y: geo.size.height * -0.75)
            }
        }
    }
}

enter image description here


Solution

  • struct ContentView: View {
        var body: some View {
            VStack(alignment: .leading) {
                Text("PETER")
                Text("PARKER").font(.largeTitle)
            }
        }
    }
    

    enter image description here