I'm trying to create a plain view with a background color in SwiftUI. But everything I can find are elements that are not plain views like Text, Button, Image, List, etc..
When I try to use View
, it shows me following error messages:
- 'View' cannot be constructed because it has no accessible initializers
- 'View' Protocol can only be used as a generic constraint because it has Self or associatedType requirements
How do I create a rectangular view with background color?
Just use the Rectangle()
As the Documentation states:
A rectangular shape aligned inside the frame of the view containing it.
Here an example of a rectangle with fixed size and background color
Rectangle()
.size(CGSize(width: 10, height: 10))
.foregroundColor(.red)
Just in case your use case is something like creating a background for a TextField view, here's a demonstration of how I did mine
The example here will create a small view with an opaque secondary background, then render on top of it a label that signifies the user to enter a location, another white rounded rectangle, and within the white rectangle a TextField().
struct InputView : View {
@State var text: String
var body: some View {
ZStack{
RoundedRectangle(cornerRadius: 15).frame(width: 310, height: 100)
.foregroundColor(.secondary)
.offset(y: -20)
ZStack{
RoundedRectangle(cornerRadius: 30).frame(width: 290, height: 40)
.foregroundColor(.white)
TextField($text, placeholder: Text("City, State, Address")) {
print(self.text)
self.didEnter.toggle()
}
.frame(width: 220, height: 40, alignment: .leading)
.offset(x: -20)
Text("Select Location:").bold().fontWeight(.medium)
.offset(y: -40)
.foregroundColor(.white)
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With