Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the listRowBackground of a collapsible List in SwiftUI

Tags:

swiftui

I have a similar or same issue like this but the answer is definitely not the answer.

Using Hacking With Swift's example:

struct Bookmark: Identifiable {
    let id = UUID()
    let name: String
    let icon: String
    var items: [Bookmark]?

    // some example websites
    static let apple = Bookmark(name: "Apple", icon: "1.circle")
    static let bbc = Bookmark(name: "BBC", icon: "square.and.pencil")
    static let swift = Bookmark(name: "Swift", icon: "bolt.fill")
    static let twitter = Bookmark(name: "Twitter", icon: "mic")

    // some example groups
    static let example1 = Bookmark(name: "Favorites", icon: "star", items: [Bookmark.apple, Bookmark.bbc, Bookmark.swift, Bookmark.twitter])
    static let example2 = Bookmark(name: "Recent", icon: "timer", items: [Bookmark.apple, Bookmark.bbc, Bookmark.swift, Bookmark.twitter])
    static let example3 = Bookmark(name: "Recommended", icon: "hand.thumbsup", items: [Bookmark.apple, Bookmark.bbc, Bookmark.swift, Bookmark.twitter])
}

struct ContentView: View {
    let items: [Bookmark] = [.example1, .example2, .example3]

    var body: some View {
        List(items, children: \.items) { row in
            Image(systemName: row.icon)
            Text(row.name)
        }
    }
}

List should be collapsible with the ability to change listRowBackground. Is this possible? I'm now wondering if Bookmark.items should be some view with the modifier .listRowBackground(..)?

like image 824
Sylar Avatar asked Oct 18 '25 02:10

Sylar


1 Answers

According to listRowBackground interface contract:

var body: some View {
    List {
        OutlineGroup(items, children: \.items) { row in
            HStack {
                Image(systemName: row.icon)
                Text(row.name)
            }
        }.listRowBackground(Color.red)
    }
}

Everything else is the same as in referenced question/answer.

Tested with Xcode 13.4 / iOS 15.5

demo

like image 57
Asperi Avatar answered Oct 21 '25 09:10

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!