Home > Net >  Swift, is there a way to align items at the end of a text?
Swift, is there a way to align items at the end of a text?

Time:10-18

I have an issue with Swift, I can't align a label at the end of a title, I've tried in different ways but without success

This is the result I get and what I'd like to obtain

 Label {
        
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Illud mihi a te nimium festinanter dictum videtur")

    } icon: {
        
            Text("  TEST  ")
                .background(Color.orange)
                .foregroundColor(.white)
        }
        
        
    } .labelStyle(RightIconLabelStyle())
struct RightIconLabelStyle: LabelStyle {
    func makeBody(configuration: Configuration) -> some View {
        HStack(alignment: .lastTextBaseline) {
            configuration.title
            configuration.icon
        }
    }
} 

I've tried also with 2 Text() elements, but it gives me error, you can't have a different background color property for a specific Text()

Text("This is a test title") Text ("TEST").background(Color.orange)

Is there a solution?

CodePudding user response:

I think your best option is to simply make "Test" an AttributedString like this:

struct AttributedStringView: View {
    var test: AttributedString {
        var attText = AttributedString("Test")
        attText.foregroundColor = .white
        attText.backgroundColor = .orange
                return attText
    }
    var body: some View {
        HStack {
            Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Illud mihi a te nimium festinanter dictum videtur")  
            Text(" ")  
            Text(test)
        }
    }
}
  • Related