First of all playground example that demonstrates the problem:
import UIKit
import SwiftUI
import PlaygroundSupport
struct MyList: View {
var body: some View {
content
}
private var content: some View {
List {
Section {
Text("hello")
}
.background(Color.red) // This only changes small area around text. Looking for Workaround 2
}
.background(Color.blue) // This doesn't work (Workaround 1)
.foregroundColor(Color.yellow)
}
init() {
// Workaround 1 - works
UITableView.appearance().backgroundColor = .blue
// Workaround 2 - nothing below helps
UITableView.appearance().sectionIndexTrackingBackgroundColor = .green
UITableView.appearance().sectionIndexBackgroundColor = .green
UITableViewCell.appearance().backgroundColor = .green
UITableViewCell.appearance().backgroundView = nil
UITableViewCell.appearance().backgroundConfiguration = .clear()
}
}
let viewController = UIHostingController(rootView: MyList())
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = viewController
Explanation:
View
has aList
, which I need to change background for. There's a well-known workaround to change it viaUITableView.appearance().backgroundColor
, which is what I do. So far so good.- I also need to change the background of the section. In the image below I want the entire section to be red, not white. White should not exist at all:
But I can't find the way to achieve this. If I add .background(Color.red)
to the Section, it only changes the small area around the text. OK, but if the white area is not part of List
, and not Section
then what is the rest of the white area?
I tried various workarounds found in SO, as listed under // Workaround 2 - nothing below helps
. None of them help.
So my question is, simply put, how do I get rid of white area in this layout.
Note:
- I would prefer to not switch away from List, unless it's the only option.
- Answers involving introspect are fine too.
CodePudding user response:
Change:
.background(Color.red) // This only changes small area around text. Looking for Workaround 2
To:
.listRowBackground(Color.red)