我试图在 SwiftUI 中创建带背景颜色的纯视图,但我找到的所有元素都不是纯视图,例如 Text、Button、Image、List 等。
当我尝试使用 View
时,它会显示以下错误消息:
- 'View' 无法构建,因为它没有可访问的初始化器
- 'View' 协议只能用作泛型约束条件,因为它具有 Self 或 associatedType 要求
如何创建一个带背景颜色的矩形视图?
只需使用Rectangle()
正如文档所述:
一个矩形形状,与其包含的视图框架内对齐。
以下是具有固定大小和背景颜色的矩形示例
Rectangle()
.size(CGSize(width: 10, height: 10))
.foregroundColor(.red)
如果您的用例是创建TextField视图的背景,这里展示了我如何实现的示例
这个示例将创建一个带有不透明次要背景的小视图,然后在其上方渲染一个标签,提示用户进入位置,另外还有一个白色圆角矩形,在白色矩形内部有一个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)
}
}
}
}
这是创建类似于UIView的另一种方法。在SwiftUI中,每个基本视图都像一个UIView。
struct CustomView : View {
var body: some View {
ZStack{
Color.red.frame(width: 300, height: 300)
Text("This is view")
}
}
}
如另一个答案所建议,您可以使用类似于Rectangle()
的形状,并设置其size
和foregroundColor
:
Rectangle()
.size(CGSize(width: 10, height: 10))
.foregroundColor(.blue)
Color
更简单:Color.blue
.frame(width: 10, height: 10)