简体   繁体   中英

How to move .listRowBackground style from the list to list element in SwiftUI?

This is my code:

var body: some View {
    List(months) { month in
        NavigationLink {
            MonthView(month: month)
        } label: {
            MonthElementView(month: month)
        }
        .listRowBackground(
            Color(uiColor: mode.underlayBackgroundColor)
                .clipped()
                .cornerRadius(10)
        )
    }
    .navigationTitle(months.first?.descriptiveYear ?? "")
}

This simply works as expected, but I need to use MonthElementView(month: month) also here:

var body: some View {
    ScrollView {
        VStack(alignment: .leading, spacing: 3, content: {
            if let month = month {
                MonthElementView(month: month)
            } else {
                Text("Nothing here yet")
            }
        })
    }
}

and here it doesnt work. Is there a way to setup.listRowBackground style directly inside my MonthElementView ?

Here is the body for MonthElementView :

var body: some View {
    VStack(alignment: .center, spacing: 8, content: {
        // some staff here
    })
    .frame(maxWidth: .infinity)
    .padding(.top, 10)
    .padding(.bottom, 10)
    .padding(.leading, 2)
    .padding(.trailing, 2)
}

background for list cell (as you have already):

            List(1..<13) { month in
                MonthElementView(month: month)
                    // list background
                    .listRowBackground(
                        Color(.gray).opacity(0.5)
                            .clipped()
                            .cornerRadius(10)
                    )
            }

background for Scollview element:

            ScrollView {
                ForEach(1..<13) { month in
                    MonthElementView(month: month)
                        // scrollview background
                        .background(
                            Color(.orange).opacity(0.7)
                                .clipped()
                                .cornerRadius(10)
                        )
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM