[英]How can I create custom shapes in swiftUI
I'm learning swiftui and I want to create some shapes in my app.我正在学习 swiftui,我想在我的应用程序中创建一些形状。
I instead of repeating my code I decided to create a function to display the shape.我没有重复我的代码,而是决定创建一个函数来显示形状。
I tried to create a func that contains the shape and call it where I need it.我试图创建一个包含形状的函数并在我需要的地方调用它。
import SwiftUI
struct HomeView: View {
var body: some View {
VStack{
HStack{
rect()
}
}
}
}
func rect() {
Rectangle()
.frame(width: 100, height: 100)
.cornerRadius(18)
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
What is my problem here, and how can I fix it so I can create different styles for buttons, textboxes, images, etc...我的问题是什么,我该如何解决它,以便我可以为按钮、文本框、图像等创建不同的样式......
To create a function for showing the view one must create @ViewBuilder function and return some View.要创建一个显示视图的函数,必须创建@ViewBuilder 函数并返回一些视图。
You need to do something like this :-你需要做这样的事情: -
@ViewBuilder func rect() -> some View {
Rectangle()
.frame(width: 100, height: 100)
.cornerRadius(18)
}
You're on the right track, instead of defining a function, define a new view:您走在正确的轨道上,而不是定义一个函数,而是定义一个新视图:
struct MyRect: View {
var body: some View {
Rectangle()
.frame(width: 100, height: 100)
.cornerRadius(18)
}
}
// Embed with 'MyRect()'
Alternatively, the func rect
in your code could have a return type some View
:或者,代码中的
func rect
可能具有返回类型some View
:
func rect() -> some View {
Rectangle()
.frame(width: 100, height: 100)
.cornerRadius(18)
}
// Embed with 'rect()'
The func rect is of type Void
, the body in your View
returns some View
. func rect 是
Void
类型,您的View
中的主体返回some View
。 You should make your function's return type conform to View
, so either:您应该使函数的返回类型符合
View
,因此:
return a Shape func rect() -> Shape {
返回一个 Shape
func rect() -> Shape {
return a View func rect() -> some View {
返回一个 View
func rect() -> some View {
Do note that if go with option number 1 you cannot return anything that is not a Shape
.请注意,如果使用选项号 1,则不能返回任何不是
Shape
的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.