How do I modify the background color of a List in SwiftUI?
Ok, I found the solution for coloring the list rows:
struct TestRow: View {
var body: some View {
Text("This is a row!")
.listRowBackground(Color.green)
}
}
and then in body:
List {
TestRow()
TestRow()
TestRow()
}
This works as I expect, but I have yet to find out how to then remove the dividing lines between the rows...
How can I change background color of each element in list depend of value inside each row
If you want to change individual rows, you have to place the .listRowBackground()
on the actual row.
List{
ForEach(taskVM.sortedDays) {day in
Section( ... ){
ForEach(day.dailyTasks.sorted(by: {$0.hour < $1.hour}), id: \.hour) {task in
HStack{
...
}
// Place it on the actual row that you want changed, otherwise
// you apply it to all rows.
// Also, this code assumes that task.color is of type Color
.listRowBackground(task.color)
.swipeActions {
...
}
}
// : Foreach (Tasks)
} // ForEach (Days)
Change background color of lists in iOS15
Change the listStyle
to .plain
. The default for iOS 14 is .plain
, and .insetGrouped
for iOS 15.
Code:
struct ContentView: View {
var body: some View {
VStack {
Text("Test")
List {
ForEach(1 ..< 20) { i in
Text(String(i))
}
}
.listStyle(.plain)
}
}
}
Result:
Modify the background colour of a List in SwiftUI?
Removing ContentView1
's init
fixes the problem.
The issue is caused by your code setting selectedBackgroundView
, but you don't need any of that init
anyway as it still functions as you intend.
SwiftUI: change background color of item in a list when it's tapped on
You need to use a .simultaneousGesture
as the list is using a DragGesture
behind the scenes.
.simultaneousGesture(
TapGesture()
.onEnded({ _ in
selectedIndex = index
})
)
Edit:
See the comments in the code.
struct HorizontalList: View {
var listItems = Array(1...10).map( { ListItem(text: "Item \($0)") })
@State var selectedIndex = 0
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 10) {
// It is good practice to always supply a ForEach with an identifiable. If you were
// to try to delete an element in the array, you can cause a crash without this.
// What Array(zip()) does is takes listItems and listItems.indices and put them together
// into an array of pairs, requiring two arguments in the ForEach, one for the item and
// one for the index. You can then use both in the loop. However, the ForEach tracks them by
// the identifiable element, not the index which is what the id: \.0 does.
ForEach(Array(zip(listItems, listItems.indices)), id: \.0) { item, index in
ListItemView(isSelected: selectedIndex == index, label: item.text)
.listRowBackground(Color.blue)
.simultaneousGesture(
TapGesture()
.onEnded({ _ in
selectedIndex = index
})
)
}
}
}
}
}
struct ListItemView: View {
// There is no reason for these to be an @State var unless this view changes them. If it does,
// it really should be a Binding to pass the data back.
let isSelected: Bool
let label: String
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 8)
.foregroundColor(isSelected ? Color.blue : Color.clear)
.frame(minHeight: 16, idealHeight: 16, maxHeight: 16)
Text(label)
}
}
}
// This becomes the item you itereate on
struct ListItem:Hashable, Identifiable {
let id = UUID()
var text: String
}
How to add background Color to List in swiftUI
If you want to change the background color you would do the following in the view containing the List
. Add this init
block in your View
. This will change everything to green.
init() {
UITableViewCell.appearance().backgroundColor = .green
UITableView.appearance().backgroundColor = .green
}
iOS 16 SwiftUI List Background
iOS 16
Update: Xcode 14b3+
Just use new modifier:
List {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
.scrollContentBackground(Color.red) // << here !!
// .scrollContentBackground(Color.clear) // << transparent !!
// .scrollContentBackground(.hidden) // << can be combined with above !!
Original
Now they use UICollectionView
for backend, so an updated workaround is to change corresponding background colors:
Main part:
extension UICollectionReusableView {
override open var backgroundColor: UIColor? {
get { .clear }
set { }
// default separators use same color as background
// so to have it same but new (say red) it can be
// used as below, otherwise we just need custom separators
//
// set { super.backgroundColor = .red }
}
}
struct ContentView: View {
init() {
UICollectionView.appearance().backgroundColor = .clear
}
//...
Test module on GitHub
SwiftUI List color background
iOS 16
Since Xcode 14 beta 3, You can change the background of all lists and scrollable contents using this modifier:
.scrollContentBackground(.hidden)
You can pass in .hidden
to make it transparent. So you can see the color or image underneath.
iOS 15 and below
All SwiftUI's List
s are backed by a UITableView
(until iOS 16). so you need to change the background color of the tableView. You make it clear
so other view
s will be visible underneath it:
struct ContentView: View {
init(){
UITableView.appearance().backgroundColor = .clear
}
var body: some View {
Form {
Section(header: Text("First Section")) {
Text("First cell")
}
Section(header: Text("Second Section")) {
Text("First cell")
}
}
.background(Color.yellow)
}
}
Now you can use Any background (including all Color
s) you want
Note that those top and bottom white areas are the safe areas and you can use the .edgesIgnoringSafeArea()
modifier to get rid of them.
Also note that List
with the .listStyle(GroupedListStyle())
modifier can be replaced by a simple Form
. But keep in mind that SwiftUI controls behave differently depending on their enclosing view.
Also you may want to set the UITableViewCell
's background color to clear
as well for plain tableviews
How to change Background Color of a View containing a List back to White in SwiftUI
you can change those colors as you wants, here a show example:(tested with Xcode 12.1 / iOS 14.1)
struct ContentView: View {
init() {
UITableView.appearance().backgroundColor = UIColor.white
}
var body: some View {
List
{
ForEach(0 ..< 20) { index in
Text("Row \(index)")
.listRowBackground(Color(UIColor.systemGray6))
}
}
}
}
Related Topics
Overriding Methods in Swift Extensions
How to Make a Swiftui List Scroll Automatically
The "++" and "--" Operators Have Been Deprecated Xcode 7.3
Send Data from Tableview to Detailview Swift
Saving Custom Swift Class With Nscoding to Userdefaults
How to Provide a Localized Description With an Error Type in Swift
How to Cast Self to Unsafemutablepointer≪Void≫ Type in Swift
What Is the Purpose of Willset and Didset in Swift
How to Convert a Date String With Optional Fractional Seconds Using Codable in Swift
Examples of Delegates in Swift
How to Use String.Substringwithrange? (Or, How Do Ranges Work in Swift)
Error-Handling in Swift-Language
Difference Between Functions and Closures
Swift Lazy Instantiating Using Self