0

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

1
  • as is, your screen should be empty :-) (due the .offset). see my answer Commented Mar 14, 2020 at 18:28

2 Answers 2

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

enter image description here

1
  • In my head, this answer was supposed to be way more complicated. Thanks! Commented Mar 15, 2020 at 0:13
0

Due to font weight differences there needs some compensation, so I would propose the approach like below

demo

struct NameText: View {
    var body: some View {
        GeometryReader { geo in
            VStack(alignment: .leading) {
                Text("PETER")
                    .fontWeight(.bold)
                    .font(.title)
                    .foregroundColor(Color(red: 30/255, green: 82/255, blue: 132/255, opacity: 1.0))
                Text("PARKER")
                    .fontWeight(.thin)
                    .font(.largeTitle)
                    .offset(x: -0.5)
            }//.border(Color.blue) // << just helper for Pixie verification
        }
    }
}
1
  • 0.5 point? this is very subjective and I am not sure, if it looks better. Change the text for "Text" or "Y" .... Commented Mar 14, 2020 at 19:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.