I have a SwiftUI view that makes use of a Section
view within a List
view. What I'm trying to do is add some drop-shadow around the section so that the section's content is clearly separated from the background of the main view. However, no matter what I've tried and Googled, I cannot get a drop-shadow to show up around the entire section. For reference, the first image below is a mockup and is what I'm trying to make my code look like. The second image is an exaggerated version of my SwiftUI view to help me debug what's going on. As you can tell, there is no drop shadow showing up.
Finally, the following is the code I have. I have tried everything that I could find, including updating the UITableView's Appearance
; however, I think I'm updating the wrong thing. Any help would be appreciated! Thank you!
Code:
struct CatalogView: View {
@ObservedObject var viewModel: CatalogViewModel
init(viewModel: CatalogViewModel) {
self.viewModel = viewModel
UITableView.appearance().backgroundColor = UIColor.cyan
UITableView.appearance().layer.masksToBounds = false
UITableView.appearance().layer.shadowColor = UIColor.red.cgColor
UITableView.appearance().layer.shadowOpacity = 1
UITableView.appearance().layer.shadowRadius = 100
UITableView.appearance().layer.shadowOffset = .init(width: 10, height: 10)
}
var body: some View {
NavigationView {
List {
Section(LocalizedStringKey("CatalogView.Program.Catalog")) {
ForEach(viewModel.programs) {
Text($0.name)
}
}
.shadow(color: Color.red, radius: 25, x: 0, y: 0)
.headerProminence(.increased)
}
.navigationTitle(viewModel.navigationTitle)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
PlusButton {
print("Hi")
}
}
}
}
.navigationViewStyle(.stack)
}
}
CodePudding user response:
Try this code
struct ContentView: View {
init() { UITableView.appearance().backgroundColor = UIColor.clear }
var body: some View {
NavigationView {
List {
Section(header: Text("Important tasks")) {
Text("Hello World")
Text("Hello World")
Text("Hello World")
}
Section(header: Text("Main tasks")) {
Text("Hello World")
Text("Hello World")
Text("Hello World")
}
}
.padding()
.shadow(color: Color.red, radius: 10, x: 5, y: 5)
.background(Color(UIColor.systemGray4).ignoresSafeArea())
.navigationTitle("Menu")
}
}
CodePudding user response:
You have to clear the background color of UITableView
because of UIKit.
init(viewModel: CatalogViewModel) {
self.viewModel = viewModel
UITableView.appearance().backgroundColor = UIColor.clear
....................
}
Add your shadow code to outside of List
not the outside of Section
and then add background color to view
List {
Section(LocalizedStringKey("CatalogView.Program.Catalog")) {
ForEach(viewModel.programs) {
Text($0.name)
}
}
.headerProminence(.increased)
}
.shadow(color: Color.red, radius: 25, x: 0, y: 0) //=====> add this line for shadow
.background(Color(UIColor.cyan).ignoresSafeArea()) //=====> add this line for background color