Member-only story

Truncating Text In SwiftUI

Cutting off text is often necessary and SwiftUI makes is easy to achieve it

Gabriel Theodoropoulos
6 min readAug 15, 2024
Photo by Eneida Nieves: https://www.pexels.com/photo/black-scissors-near-thread-reel-on-white-book-page-803927/

Text is the most common kind of content that apps contain. We deal with all sorts of text length everyday, but when it comes to long text we often need to cut it off and display just a part of it. Along with that, users usually get an option to expand and view the long text, or collapse and keep it truncated.

In this post I am going to demonstrate two ways that will let you achieve truncation easily, and an additional approach where you can simulate (fake) truncation by fetching and presenting a substring of the original string. As a bonus chapter, I’ll also show you how to expand and collapse truncated text, mostly because truncation and text expansion go together as features into an app.

Truncating text based on number of lines

Initially, let’s begin with a small code example; a Text view that displays some long text:

struct ContentView: View {
let longText = “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…

--

--

Gabriel Theodoropoulos
Gabriel Theodoropoulos

Written by Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev

No responses yet