SwiftUI: How-to append view to ending of multiline text?

Viewed 455

Current

I have something like the following:

Short text with badge:

enter image description here

It's done simple with HStack atm:

HStack {
    Text("Lorem ipsum dolor sit amet.")
        .font(.title2)
    Text("foo")
        .font(.system(size: 14, weight: .bold))
        .foregroundColor(.white)
        .padding(.horizontal, 4)
        .padding(.vertical, 2)
        .background(Color.red)
        .cornerRadius(5)
}

My Problem is that the main text is multiline and if it wraps, it looks like this:

Larger multiline text with badge:

enter image description here

Goal

But my goal is that the foo badge is always displayed after the last word of the main text, which should look like this:

Goal: Solution like Text + Text:

enter image description here

In other words I want the same behaviour as if I would use the concatenating feature of SwiftUI's Text (Text() + Text()), but I can't use that because of the formatting of the badge. The formatting modifiers like background() will change the return type to View and then the + operator doesn't work anymore.

What is the most elegant solution to achieve my goal? I would prefer not using UIKit.

1 Answers

This below solution gives the result but, the badge will be at the end of the line. If, it is static text, you can use offset(x: ) to achieve that manually.

ZStack(alignment: .bottomTrailing) {
       Text("But my goal is that the foo badge is always displayed after the last word of the main text, which should look like this:")
           .font(.title2)

       Text("foo")
           .font(.system(size: 14, weight: .bold))
           .foregroundColor(.white)
           .padding(.horizontal, 4)
           .padding(.vertical, 2)
           .background(Color.red)
           .cornerRadius(5)
           .alignmentGuide(.bottom) { d in d[.bottom] }
           // .offset(x: 50)
}
Related