Home > database >  Is there a way to let the user decide between two ListStyles in SwiftUI
Is there a way to let the user decide between two ListStyles in SwiftUI

Time:01-11

What I am trying to accomplish is a list which can change its style based on the user's preference.

I have a @AppStorage property which can be changed in the settings to use .plain or .insetGrouped in the listStyle modifier.

I have tried using a ternary operator like in the code below, but I get a type mismatch error. Here's my code:

import SwiftUI

struct ContentView: View {
    
    @AppStorage("listStyle") private var listStyle: Bool = false
    
    var body: some View {
        NavigationStack {
            List {
                ForEach(1...10, id: \.self) { i in
                    Section {
                        Text("Item \(i)")
                    }
                }
            }
            .listStyle(listStyle ? .plain : .insetGrouped)
        }
    }
}

CodePudding user response:

You can use a custom ViewModifier to apply the appropriate list style based on the boolean like this:

struct ContentView: View {
    
    @AppStorage("listStyle") private var isListPlain: Bool = false
    
    var body: some View {
        NavigationStack {
            List {
                ForEach(1...10, id: \.self) { i in
                    Section {
                        Text("Item \(i)")
                    }
                }
            }
            .myListStyle(isListPlain: isListPlain)
        }
    }
}

struct MyListViewModifier : ViewModifier {
    let isListPlain : Bool
    func body(content: Content) -> some View {
        if(isListPlain){
            content.listStyle(.plain)
        }else{
            content.listStyle(.insetGrouped)
        }
    }
}

extension View {
    func myListStyle(isListPlain : Bool) -> some View {
        modifier(MyListViewModifier(isListPlain: isListPlain))
    }
}
  • Related