I have two Text()
s in SwiftUI. One is a long multi-line text, left aligned. The other is a short one line text, right aligned. I’d like to arrange the two in the following way.
- If there is enough space on the last line of the multi-line text, place the single line text in the last line:
- If there is not enough space, place it below the multi-line text:
The code below renders the second screenshot, but it can’t put the second text on the same line if there is space like in the first screenshot.
<code>struct TextTest: View {
var body: some View {
VStack(alignment: .trailing){
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sa laborum.")
Text("(c) 2024")
.font(.caption)
}
.padding()
Spacer()
}
}
</code>
<code>struct TextTest: View {
var body: some View {
VStack(alignment: .trailing){
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sa laborum.")
Text("(c) 2024")
.font(.caption)
}
.padding()
Spacer()
}
}
</code>
struct TextTest: View {
var body: some View {
VStack(alignment: .trailing){
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sa laborum.")
Text("(c) 2024")
.font(.caption)
}
.padding()
Spacer()
}
}
Is there a way to handle both cases automatically in SwiftUI?
Two things that don’t work:
- I can’t just add the two text together (
Text("a")+Text("b")
) as the second text will not be right aligned. - ParagraphStyles of AttributedStrings are not supported in SwiftUI.