Search code examples
stringswiftuitext

How to remove 3 dots after end of line limit


In SwiftUI,

Text("a \n b \n c \n d \n e")
     .lineLimit(3)

In SwiftUI, the above code shows output including 3 dots in the end. Output:

a
b
c...

But my target is to show the output without dots like this - Target:

a
b
c

Solution

  • implement the following way.

    Text("1\n 2 \n 3 \n 4 \n 5".truncateToLineLimit(3))
    
    extension String {
        func truncateToLineLimit(_ lineLimit: Int) -> String {
            var truncatedString = ""
            let lines = self.components(separatedBy: "\n").prefix(lineLimit)
            for line in lines {
                truncatedString += line.trimmingCharacters(in: .whitespacesAndNewlines)
                if line != lines.last {
                    truncatedString += "\n"
                }
            }
            return truncatedString
        }
    }