如何在Swiftui中创建自定义形状
我正在学习Swiftui,我想在应用程序中创建一些形状。
我没有重复代码,而是决定创建一个函数以显示形状。
我试图创建一个包含形状的函数,并将其称为我需要的位置。
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()
}
}
我的问题是什么,我该如何修复它,以便可以为按钮,文本框,图像等创建不同的样式...
I'm learning swiftui and I want to create some shapes in my app.
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在正确的轨道上,而不是定义函数,而是定义一个新视图:
或者,代码中的
func rect
可以具有返回类型某些视图
:You're on the right track, instead of defining a function, define a new view:
Alternatively, the
func rect
in your code could have a return typesome View
:要创建一个函数以显示视图,必须创建@ViewBuilder函数并返回一些视图。
您需要做这样的事情: -
To create a function for showing the view one must create @ViewBuilder function and return some View.
You need to do something like this :-
func rect是类型
void
,view> view
返回某些视图
中的正文。您应该使函数的返回类型符合view
,所以要么:返回形状
func rect() - >形状{
返回视图
func rect() - >一些查看{
请注意,如果使用选项号1,则无法返回任何不是
shape
的东西。The func rect is of type
Void
, the body in yourView
returnssome View
. You should make your function's return type conform toView
, so either:return a Shape
func rect() -> Shape {
return a View
func rect() -> some View {
Do note that if go with option number 1 you cannot return anything that is not a
Shape
.