Ungrace
Ungrace

Reputation: 294

SwiftUI How to adjust brightness of background color, and not all subviews

How do I make it so the brightness only affects the view's background color and not its subviews? I want the text to stay white, but the background to get darker

this code

struct ListCell: View {
    let brightness : Double
    var body: some View {
        
        VStack {
            HStack {
                Image(systemName: "music.house")
                    .resizable()
                    .aspectRatio(1, contentMode: .fit)
                    .frame(height: 50)
                    .padding()
                
                VStack(alignment: .leading) {
                    Text("List Name")
                        .padding(.bottom,5)
                        .foregroundColor(Color.white)
                    
                    Text("A long subtitle which extends more than a line")
                        .foregroundColor(Color.white)
                }
            }.background(Color.blue).brightness(brightness)
        }
    }
}

makes This happen

and this code

struct ContentView: View {
    
    @State var lists : [Listi] = theLists
    
    var body: some View {
        var color = 0.0
            List(lists) { list in
                ListCell(brightness: color).onAppear(perform: {
                    color -= 0.1
                })
            }
            .onAppear(perform: {
                UITableView.appearance().separatorColor = .clear
            })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

makes this happen makes this happen

Upvotes: 3

Views: 4843

Answers (1)

aheze
aheze

Reputation: 30278

If you do:

HStack {
 ... 
}
.background(Color.blue)
.brightness(brightness)

The order matters, so you can think of it as

  1. HStack
  2. HStack + blue background
  3. HStack + blue background + custom brightness

... you're applying the brightness modifier to the HStack + blue background. Instead, if you only want the blue background to get the brightness modifier, just attach it like this instead:

HStack {
 ... 
}
.background(
    Color.blue
    .brightness(brightness)
)

Color conforms to View, so you are allowed to add view modifiers like brightness to it.

Upvotes: 6

Related Questions