How to expand/collapse text in SwiftUI

Guru
2 min readNov 16, 2023

I learnt a few intersting bits of coding hacks while building my recent SwiftUI app (dedicated to my favourite Arsenal manager, Arsene Wenger. You can download it here for free). One of them was how easy it is to expand and collapse text. Unbelievable! Here’s the code, in case you want to try it in your app. When I wanted to achieve a similar effect a few years back, the code a helpful developer shared was so long and complicated I gave up. Thanks to SwiftUI, it can be done in literally a few lines of code.


import SwiftUI

struct ExpCollapseView: View {
@State private var expCollapse = false

var body: some View {
VStack{
Section(header: Text("Title of paragraph").font(.title).bold()){

if expCollapse{

Text("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.")
}
}.onTapGesture {
self.expCollapse.toggle()
}

}

}
}

#Preview {
ExpCollapseView()
}

Here’s what it looks like:

Thanks SwiftUI team for making the learning curve easier!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Guru
Guru

Written by Guru

Author| Senior freelance writer| Novice iOS and Android Developer| Interests: Classical guitar enthusiast|Pottery | https://about.me/gurun

No responses yet

Write a response