Suyash
Suyash

Reputation: 335

How to vertically align emoji with text in iOS using SwiftUI?

I have emoji inside Text view (SwiftUI) and it doesn't vertically align with the rest of the text.

Code I have:

var body: some View {
VStack {
  Text("PUT THE BULLLS EYE 🎯 AS CLOSE AS YOU CAN TO THE")
    .bold()
    .kerning(2.0)
    .multilineTextAlignment(.center)
    .lineSpacing(4.0)
    .font(.system(size: 13, weight: .medium, design: .default))

  Text("89")
  HStack {
    Text("1")
    Slider(value: Binding.constant(50), in: 1.0...100.0)
    Text("100")
  }
  Button(action: {}) {
    Text("Hit Me!")
  }
}

Notice in the screenshot target emoji 🎯 sits below the text and I want to align with the rest of the text in the same line. Any ideas?

Screenshot of the View

Upvotes: 0

Views: 623

Answers (1)

jnpdx
jnpdx

Reputation: 52555

You can use + to attach Text components. Then, you can change the baseline of one of the elements:

Group {
   Text("PUT THE BULLLS EYE ").bold().kerning(2.0)
   + Text("🎯").baselineOffset(3) + Text(" AS CLOSE AS YOU CAN TO THE").bold().kerning(2.0)
}
.multilineTextAlignment(.center)
.lineSpacing(4.0)
.font(.system(size: 13, weight: .medium, design: .default))

The version I have above is fragile since it depends on a magic number (3) for the current font size, but you could do some work to calculate what it would be for other sizes.

Upvotes: 3

Related Questions