SwiftUIでbackgroundの指定で思ったように塗りつぶしてくれなかったりしたので、どこで指定したらどのように塗り潰されるかを調べてみました。
コードとView
struct ContentView: View {
var body: some View {
VStack {
Spacer()
Text("Hello world!")
.foregroundColor(Color.white)
.background(Color.green)
.frame(maxWidth: .infinity, minHeight: 50)
.background(Color.blue)
.padding()
.background(Color.orange)
Spacer()
}.frame(width: 320, height: 100)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())
解説
-
frame
の前にbackground
を指定すると、テキストギリギリの範囲で塗りつぶされました(緑色) -
frame
の後にbackground
があり、かつbackground
の後にpadding
がある場合は、padding
分内側で塗りつぶされました(青) -
padding
の後にbackground
を指定すると、padding
も無視した領域で塗りつぶされました(オレンジ)
このようにbackground
の位置に注意することで、想定通りの塗りつぶしができそうです。