SwiftUI - How do I change the background color of a View?

后端 未结 13 1153
渐次进展
渐次进展 2020-12-13 11:53

I\'m beginning to try out SwiftUI and I\'m surprised that it doesn\'t seem to be straightforward to change the background color of a View. How do y

13条回答
  •  囚心锁ツ
    2020-12-13 12:11

    I like to declare a modifier for changing the background color of a view.

    extension View {
      func background(with color: Color) -> some View {
        background(GeometryReader { geometry in
          Rectangle().path(in: geometry.frame(in: .local)).foregroundColor(color)
        })
      }
    }
    

    Then I use the modifier by passing in a color to a view.

    struct Content: View {
    
      var body: some View {
        Text("Foreground Label").foregroundColor(.green).background(with: .black)
      }
    
    }
    

提交回复
热议问题