Josh Prewer

Creating a Collapsable View in SwiftUI

Collapsable content is common requirement in modern apps. With SwiftUI, achieving this functionality is easy using custom view modifiers. This modifier allows you to make a view collapsible by leveraging SwiftUI's powerful composability and view modifier features. Let's break down the code piece by piece to understand its functionality and how it can be used in your SwiftUI applications.

Creating a Custom ViewModifier

struct CollapsableViewModifier: ViewModifier {

    @Binding var isCollapsed: Bool
    let collapsedHeight: CGFloat

    func body(content: Content) -> some View {
            .fixedSize(horizontal: false, vertical: true)
            .frame(height: height, alignment: .top)

private extension CollapsableViewModifier {

    var height: CGFloat? {
        isCollapsed ? collapsedHeight : nil

We define a new struct called CollapsableViewModifier that conforms to the ViewModifier protocol.

The body(content:) function specifies how the view modifier should modify the content. In this case, we use the .fixedSize(horizontal:vertical:) method to allow the view to grow vertically but not horizontally. Then, we set the frame height using the computed property height, align it to the top, and finally apply the .clipped() method to cut off any overflowing content.

Extending the View Protocol

extension View {
public func collapsable(isCollapsed: Binding<Bool>, collapsedHeight: CGFlot) -> some View {
                isCollapsed: isCollapsed,
                collapsedHeight: collapsedHeight

In this section, we are extending the View protocol by adding a new method called collapsable. This method takes two parameters:

  • isCollapsed: A Binding that indicates whether the view should be collapsed or not,
  • collapsedHeight: A CGFloat that specifies the height of the collapsed view.

The method applies the CollapsableViewModifier to the view and returns the modified view.


To wrap it all up, you can now create collapsable views by just apply this .collapsable view modifier!

struct CollapsableView: View {

    @State var isCollapsed = false

    var body: some View {
        VStack {
        .collapsable(isCollapsed: $isCollapsed, collapsedHeight: 10)

By extending the View protocol and implementing a ViewModifier, we provide a reusable and elegant solution for creating collapsable views in SwiftUI.

Tagged with: