如何在SwiftUI中获得完美的圆角

时间:2019-11-24 02:34:07

标签: swiftui cornerradius

使用UIKit,可以使用以下方法为控件(例如按钮)提供完美的圆角(在每边形成一个圆):

for (i in 1:length(alpha)) { 
  for (j in 1:length(beta)) {
    Xij <- alpha[i] + beta[j]
    matrix[i,j] <- Xij
  }
}

如何在SwiftUI中获得相同的结果?由于视图的定义是即时进行的,因此我不确定如何除非手动设置即可引用该帧大小(这不是这里的要求)。

exampleButton.cornerRadius = exampleButton.frame.size.height/2

5 个答案:

答案 0 :(得分:6)

对此的另一种解决方案是使用形状,在这种情况下为Capsule形状,并使用clipShape修饰符

以已经提到的示例为例:

Button(action: {
// ...
}) {
Text("I'm a Button")
    .padding(.horizontal, 10)
    .background(Color.red)
    .clipShape(Capsule())
}

可以调整其中的填充,以便您的视图看起来像您想要的那样。胶囊始终具有完美圆润的末端这一点。在这种情况下,我不希望文本太靠近圆角边缘,因此我在侧面上使用了一些填充。

要记住的一点是,在SwiftUI中,应用修饰符的顺序非常重要。

答案 1 :(得分:3)

您需要将其定义为一个正方形,然后将圆角四舍五入,如下所示:

Button(action: {
// ...
}) {
Text("I'm a Button")
    .frame(width:150, height:150)
    .background(Color.red)
    .cornerRadius(.infinity)

}

PS。添加了一些可见性的背景颜色

答案 2 :(得分:1)

使用 XCode 12.4

对于发现此问题并试图找出如何制作带有圆角的按钮(无论是否像胶囊一样完全圆形)的任何人:

            Button(action: {
                // Do whatever
            }) {
                Spacer()
                Text("Log In")
                    .font(.title2)
                    .padding()
                    .foregroundColor(.white)
                Spacer()
            }
            .background(Color(UIColor.systemBlue))
            .clipShape(RoundedRectangle(cornerRadius: 12))
            .padding()

无需为叠加形状大惊小怪。

Rounded Button

答案 3 :(得分:0)

另一种解决方案是使用geometry reader,它将占用屏幕的高度或宽度,并允许您对其进行除法,乘除或加法。

使用示例,就像这样:

Geometry Reader { Geometry in
Button(action: {
    // ...
}) {
    Text("I'm a Button")
}
.cornerRadius(geometry.size.width / 2)

}

它与frame.size.height最相似。

答案 4 :(得分:-1)

enter image description here

Button(action: {
        print("Exit the onboarding")
    }) {
        HStack (spacing: 8) {
            Text("NEXT")
                .foregroundColor(Color("ColorAccentOppBlack"))
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 10)
        .foregroundColor(Color("ColorYellowButton"))
    } //: BUTTON
    .accentColor(Color("ColorYellowButton"))
    .background(Color("ColorYellowButton"))
    .cornerRadius(10)