UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Force truncation of Text in a ListView

Forums > SwiftUI

Greetings,

I'm almost done with my app, but I have a detail that is bothering and I couldn't find a way to resolve that. I have a ListView that is generated based on Core Data content and this works fine. It's about how a piece of text is displayed in it that I have a "visual" issue.

Some of the text gets truncated, and some not, making some items in the list a 2-liner instead of a 1-liner.

I would like ideally to get all the line, if the text is too long, like the 1 line in the list here: https://ibb.co/RptVWh0

Here is the piece of code that displays that part at the moment:

HStack {
                            Image(systemName: "network")
                            Text(host.hostName!)
                            Spacer()
                            Text(String(host.hostPort))
                            Spacer()
                            if host.hostStatus == "Success" {
                                Image(systemName: "checkmark.circle.fill")
                                    .foregroundColor(.green)
                            } else if host.hostStatus == "Unchecked" {
                                Image(systemName: "questionmark.circle.fill")
                                    .foregroundColor(.yellow)
                            } else {
                                Image(systemName: "x.circle.fill")
                                        .foregroundColor(.red)
                            }
                        }

Ideally I would like the "line" to be split in 4, with each of them having a dedicated space: the icon at the beginning and at the end should be fixed size, since they won't change and the port number can be fixed as well, as it should not be more than 6 digits. So once this is fixed, the Text shoud occupy the rest and if the text is too long, then truncate with the ... at the end of it.

Any hint appreciated :) Thank you

1      

Try this:

Text(host.hostName!)
  .lineLimit(1)
  .truncationMode(.tail)

3      

Perfect, worked like a charm, thanks a lot :)

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.