SwiftUI:如何获得完美圆角的视图
SwiftUI: How to Get a View with Perfectly Rounded Corners
使用 UIKit,可以使用以下方法为控件(例如按钮)提供完美的圆角(在每边形成一个圆圈):
exampleButton.cornerRadius = exampleButton.frame.size.height/2
如何使用 SwiftUI 视图实现相同的结果?
因为视图是动态定义的,所以我不确定如何引用该帧大小,除非它是手动设置的(这不是这里的期望)。
Button(action: {
// ...
}) {
Text("I'm a Button")
}
.cornerRadius(???)
您需要将其定义为正方形,然后在角上进行圆角处理,如下所示:
Button(action: {
// ...
}) {
Text("I'm a Button")
.frame(width:150, height:150)
.background(Color.red)
.cornerRadius(.infinity)
}
PS。为可见性添加了一些背景颜色
另一种解决方案是使用形状,在本例中为 Capsule
形状,并使用 clipShape
修饰符
拿上面的例子来说,就是这样:
Button(action: {
// ...
}) {
Text("I'm a Button")
.padding(.horizontal, 10)
.background(Color.red)
.clipShape(Capsule())
}
可以调整其中的填充,以便您的视图看起来像您想要的那样。胶囊的末端将始终完美圆润。在这种情况下,我不希望文本太靠近圆形边缘,所以我在两侧应用了一些填充。
需要记住的一点是,在 SwiftUI 中,修饰符的应用顺序非常重要。
另一种解决方案是使用 geometry reader
,它将获取屏幕的高度或宽度,并允许您对其进行除法、乘法减法或加法运算。
使用这个例子,它会是这样的:
Geometry Reader { Geometry in
Button(action: {
// ...
}) {
Text("I'm a Button")
}
.cornerRadius(geometry.size.width / 2)
}
与frame.size.height
最相似。
工作于 XCode12.4
对于发现此问题并试图找出如何制作圆角按钮(无论是否像胶囊一样完全圆形)的任何人:
Button(action: {
// Do whatever
}) {
Spacer()
Text("Log In")
.font(.title2)
.padding()
.foregroundColor(.white)
Spacer()
}
.background(Color(UIColor.systemBlue))
.clipShape(RoundedRectangle(cornerRadius: 12))
.padding()
无需为叠加形状烦恼。
使用 UIKit,可以使用以下方法为控件(例如按钮)提供完美的圆角(在每边形成一个圆圈):
exampleButton.cornerRadius = exampleButton.frame.size.height/2
如何使用 SwiftUI 视图实现相同的结果?
因为视图是动态定义的,所以我不确定如何引用该帧大小,除非它是手动设置的(这不是这里的期望)。
Button(action: {
// ...
}) {
Text("I'm a Button")
}
.cornerRadius(???)
您需要将其定义为正方形,然后在角上进行圆角处理,如下所示:
Button(action: {
// ...
}) {
Text("I'm a Button")
.frame(width:150, height:150)
.background(Color.red)
.cornerRadius(.infinity)
}
PS。为可见性添加了一些背景颜色
另一种解决方案是使用形状,在本例中为 Capsule
形状,并使用 clipShape
修饰符
拿上面的例子来说,就是这样:
Button(action: {
// ...
}) {
Text("I'm a Button")
.padding(.horizontal, 10)
.background(Color.red)
.clipShape(Capsule())
}
可以调整其中的填充,以便您的视图看起来像您想要的那样。胶囊的末端将始终完美圆润。在这种情况下,我不希望文本太靠近圆形边缘,所以我在两侧应用了一些填充。
需要记住的一点是,在 SwiftUI 中,修饰符的应用顺序非常重要。
另一种解决方案是使用 geometry reader
,它将获取屏幕的高度或宽度,并允许您对其进行除法、乘法减法或加法运算。
使用这个例子,它会是这样的:
Geometry Reader { Geometry in
Button(action: {
// ...
}) {
Text("I'm a Button")
}
.cornerRadius(geometry.size.width / 2)
}
与frame.size.height
最相似。
工作于 XCode12.4
对于发现此问题并试图找出如何制作圆角按钮(无论是否像胶囊一样完全圆形)的任何人:
Button(action: {
// Do whatever
}) {
Spacer()
Text("Log In")
.font(.title2)
.padding()
.foregroundColor(.white)
Spacer()
}
.background(Color(UIColor.systemBlue))
.clipShape(RoundedRectangle(cornerRadius: 12))
.padding()
无需为叠加形状烦恼。