iPadawan
iPadawan

Reputation: 1110

Click accepting everywhere on a section to open and close section

For macOS I use the

.contentShape(Rectangle()) 

modifier on other items like the TabBar to make the whole view accepting the click. However I can't get that to work in the section of a list. I don't know how to extend the open and close icon view to accept click to the whole section; not only the text but also the empty space between the text and icon. I use modifiers extensions to create my own modifiers. Here I got just two samples. but how can I reach the whole section?

import SwiftUI

struct Label_Extension: View {
    var body: some View {
        List() {
            Label("Bikes and Prices", systemImage: "banknote")
                .labelStyle(.tabBarTag)
        }
        List {
            Section (header: Label("Bikes and Prices", systemImage: "banknote")
                .labelStyle(.sideBarSection)) {
                    Text("Buy and Sell")
                    Label("Bikes and Prices", systemImage: "banknote")
                        .labelStyle(.sideBarSection)
                }
        }.listStyle(.sidebar)
    }
}


extension LabelStyle where Self == SideBarSectionLabelStyle {
    static var sideBarSection: SideBarSectionLabelStyle {
        SideBarSectionLabelStyle()
    }
}

extension LabelStyle where Self == TabBarTagLabelStyle {
    static var tabBarTag: TabBarTagLabelStyle {
        TabBarTagLabelStyle()
    }
}

struct TabBarTagLabelStyle: LabelStyle {
    private var iconWidth = 14.0
    
    func makeBody(configuration: Configuration) -> some View {
        HStack {
            configuration.icon
                .foregroundColor(.secondary)
                .frame(width: iconWidth)
            configuration.title
                .foregroundColor(.secondary)
        }
        .padding(8)
        .background(in: RoundedRectangle(cornerRadius: 5, style: .continuous))
        .compositingGroup()
        .font(.caption)
    }
}

struct SideBarSectionLabelStyle: LabelStyle {
    private var iconWidth = 18.0
    
    func makeBody(configuration: Configuration) -> some View {
        HStack {
            configuration.icon
                .foregroundColor(.red)
                .frame(width: iconWidth)
            configuration.title
                .foregroundColor(.red)
        }
        .padding(6)
        .contentShape(Rectangle())
        .font(.title2)
    }
}

#Preview {
    Label_Extension()
}

How can I solve this? What do I miss.


enter image description here

enter image description here

Upvotes: 2

Views: 32

Answers (0)

Related Questions