BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 38 - How to hide an empty section

Forums > 100 Days of SwiftUI

Hello everyone!

I added a title for each of my sections. But when a section is empty, the tittle doesn't disappear. Here is my code.

import SwiftUI

struct ContentView: View {
    @StateObject var expenses = Expenses()
    @State private var showingAddExpense = false
    @State private var price = 0.0
    @State private var emptySection = false // 

    let type = "Personal"

    var body: some View {
        NavigationView {
            List{
                Section(header: Text(emptySection ? "Personal" : "")) {      //  I tried with it but it doesn't work
                    ForEach (expenses.items) { item in
                        if item.type == type {
                            HStack {
                                VStack(alignment: .leading) {
                                    switch item.amount {
                                    case 0...10:
                                        Text(item.name)
                                            .font(.headline)
                                            .foregroundColor(.mint)
                                        Text(item.type)
                                    case 11...100:
                                        Text(item.name)
                                            .foregroundColor(.indigo)
                                            .foregroundColor(.mint)
                                        Text(item.type)
                                    default:
                                        Text(item.name)
                                            .foregroundColor(.red)
                                            .foregroundColor(.mint)
                                        Text(item.type)
                                    }
                                }
                                Spacer()

                                Text(item.amount, format: .currency(code: Locale.current.currencyCode ?? "PLN"))
                            }
                        }
                    }
                    .onDelete(perform: removeItem)
                }

              // THE REST OF THE CODE 

2      

TooMas asks:

How do you hide a Section in a List, if it is empty?

You pasted an awful lot of code, but much of it has nothing to do with your question. At times like this, it might be useful to Step Away from your Project!

Instead, concentrate on the function you want with a small project. This is a great job for Playgrounds! Use the Playground to try out the functions and options. Here's some practice code, ready for you to paste into a new project. This has two toggles. One hides the content of a Section, leaving the Section header. The other completely hides a Section from the View.

Experiment with options! Please return and let us know how you solved this!

// Fun with Sections!
// Some practice code for TooMas
// Created by Obelix on 28 APR 2022.

import SwiftUI

struct EmptySectionView: View {
    @State private var showSection1       = true  // Show or hide entire section
    @State private var showSection1Detail = true  // Show or hide the detail

    var body: some View {
        List {
            Section(header: Text("Options")) {
                Toggle("Hide Section 1", isOn: $showSection1)
                Toggle("Hide Section 1 Detail", isOn: $showSection1Detail)
            }
            // Show or Hide the entire section -----------------------
            if showSection1 {
                Section(header: Text("Header 1")) {
                    // Show or Hide the section detail
                    if showSection1Detail {
                        Text("๐Ÿ‡ฌ๐Ÿ‡ง *Hello* from Section 1")
                        Text("๐Ÿ‡ฎ๐Ÿ‡น *Ciao* from Section 1")
                        Text("๐Ÿ‡ฉ๐Ÿ‡ช *Servus* from Section 1")
                    }
                }
            } // ------------------------ End of Section 1
            Section(header: Text("Header 2")) {
                Text("๐Ÿ‡ฌ๐Ÿ‡ง *Hello* from Section 2")
                Text("๐Ÿ‡ฎ๐Ÿ‡น *Ciao* from Section 2")
                Text("๐Ÿ‡ฉ๐Ÿ‡ช *Servus* from Section 2")
            }
        }
        .animation(.easeInOut, value: showSection1Detail) // Ugh! Animation is buggy.
        .animation(.easeInOut, value: showSection1) // sliding animation
        Spacer()
    }
}

2      

Thank you for your answer :)

Maybe I didn't make myself clear. In the task of the 38th day, we created an application in which we add our expenses. I would like the title of the section to appear when a new expense is added. And disappeared when the section became empty.

I would like to do this without using "isOn"

I hope you can understand me. English is not my forte

2      

Toomaa clarifies his question:

I would like the section title to appear when a new expense is added and disappear when the section becomes empty.

Your use case depends on the state of your data model. Do you have expenses or not? You can answer this question by asking your expenses array if it is EMPTY.

Then you make a decision to SHOW the section if the sectionIsNotEmpty.
Otherwise, don't show the section.

DO NOT create a sectionEmpty var that you have to manually set and reset. Make it a computed property.

// Fun with Sections! Part Deux
// Some practice code for TooMas
//
//  Created by Obelix on 28 APR 2022.

import SwiftUI

struct EmptySectionView: View {
    @State private var showExpenses = true  // Toggle expenses

    var expenses: [String] {
        if showExpenses {
            // expenses.isEmpty = false
            return ["๐Ÿ‡ฌ๐Ÿ‡ง Hello from Section 1", "๐Ÿ‡ฎ๐Ÿ‡น Ciao from Section 1", "๐Ÿ‡ฉ๐Ÿ‡ช Servus from Section 1"]
        }
        return []  // expenses.isEmpty = true
    }

    // Computed property to tell you if the section has data or not.
    var sectionIsNotEmpty: Bool {
        !expenses.isEmpty // Just making a point. This makes code easier to understand.
    }

    var body: some View {
        List {
            // This is just a test mechanism. Add or remove test data.
            Section(header: Text("Test Mechanics")) {
                Toggle("Show Expenses:", isOn: $showExpenses)
            }
            // Show section only if you have expenses
            if sectionIsNotEmpty {
                Section(header: Text("Header 1")) {
                    ForEach ( expenses, id: \.self ) {  Text( $0 ) }
                }
            }
            Section(header: Text("Header 2")) {
                Text("๐Ÿ‡ฌ๐Ÿ‡ง *Hello* from Section 2")
                Text("๐Ÿ‡ฎ๐Ÿ‡น *Ciao* from Section 2")
                Text("๐Ÿ‡ฉ๐Ÿ‡ช *Servus* from Section 2")
            }
            Section(header: Text("Expenses Count")) {
                Text("Expenses array has \(expenses.count) items.")
            }
        }
        .animation(.easeInOut, value:  expenses.count) // sliding animation
        Spacer()
    }
}

3      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.