Swift UI中带有圆角的按钮边框

101

我试图设置一个按钮的圆角边框,但是按钮的边框不正确。

代码:

Button(action: {
        print("sign up bin tapped")          
}) {
    Text("SIGN UP")
      .frame(minWidth: 0, maxWidth: .infinity)
      .font(.system(size: 18))
      .padding()
      .foregroundColor(.white)
 }
  .border(Color.white, width: 2)
  .cornerRadius(25)

输出:

enter image description here

正如您所看到的那样,角落处的边框被切掉了。

有什么建议我做错了什么吗?


你可以尝试参考这个链接:https://www.appcoda.com/swiftui-border/ - Aira Samson
14个回答

1
这对我有用。
Button(action: {
  print("Exit the onboarding")
}) {
HStack (spacing: 8) {
  Text("NEXT")
  .foregroundColor(Color("ColorAccentOppBlack"))
}
.padding(.horizontal, 16)
.padding(.vertical, 10)
.foregroundColor(Color("ColorYellowButton"))
.background(
   Capsule().strokeBorder(Color("ColorYellowButton"), lineWidth: 1.25)
 )
} 
.accentColor(Color("ColorYellowButton"))

1
你应该使用 Capsule。这是 SwiftUI 内置的功能,它会处理圆角。完整的实现在这里 https://redflowerinc.com/how-to-implement-rounded-corners-for-buttons-in-swiftui/
public struct ButtonStyling : ButtonStyle {
    public var type: ButtonType
    public init(type: ButtonType = .light) {
        self.type = type
    }
    public func makeBody(configuration: Configuration) -> some View {
        configuration.label.foregroundColor(Color.white)
            .padding(EdgeInsets(top: 12,
                                   leading: 12,
                                   bottom: 12,
                                   trailing: 12))
               .background(AnyView(Capsule().fill(Color.purple)))
               .overlay(RoundedRectangle(cornerRadius: 0).stroke(Color.gray, lineWidth: 0))
    }
}

enter image description here


1
也许需要对答案进行更新,因为一些好的答案正在使用.cornerRadius(radius: CGFloat)视图修饰符,而根据Xcode的提示,这个修饰符将很快被弃用。
建议使用.clipShape(..)
以下是如何实现圆角而不使用.overlay(这在过去对我来说也感觉很笨拙)和.cornerRadius(..)
Button {
    // button action
} label: {
    Text("BUTTON TITLE")
        .bold()
        .padding(.vertical, 2)
        .padding(.horizontal, 8)
}
.background(Color.blue)
.foregroundColor(.white)
.clipShape(RoundedRectangle(cornerRadius: 5))

你当然可以使用除了RoundedRectangle之外的其他形状。例如:Circle()。

这是最好的答案。 - undefined

-1

想知道如何添加具有颜色渐变和圆角半径的按钮边框吗?以下是实现方式。

  Button(action: {self.isCreateAccountTapped = true},label: {Text("Create an Account")
.foregroundColor(Color("TextThemeColor36"))}
 )
.frame(height: 44)
.frame(width: 166)
.background(Color.clear)
.cornerRadius(8)
.overlay(RoundedRectangle(cornerRadius: 10)
.stroke(LinearGradient(gradient: Gradient(colors: [Color("BtnGradientClr1"),Color("BtnGradientClr2"),Color("BtnGradientClr3")]), startPoint: .leading, endPoint: .trailing)))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接