3

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.

koen
  • 5,383
  • 7
  • 50
  • 89
Stitch
  • 107
  • 2
  • 8
  • Probably this https://stackoverflow.com/questions/59531122/how-to-use-attributed-string-in-swiftui can be helpful. Second answer. – ezaji Dec 02 '20 at 15:02
  • @ezaji You mean the third answer, the custom AttributedText implementation? Second answer, the + operator I can't use because of the background and padding stuff changing the return type, like I've described. – Stitch Dec 02 '20 at 15:38
  • 1
    Yes, third answer is more appropriate for your purpose. – ezaji Dec 03 '20 at 04:15

1 Answers1

0

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)
}
Navemics
  • 51
  • 6