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!

--

--

Guru

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