簡體   English   中英

Swift UI 中具有圓角半徑的按鈕邊框

[英]Button border with corner radius in Swift UI

我正在嘗試為按鈕設置圓角邊框,但按鈕的邊框不正確。

代碼:

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)

Output:

在此處輸入圖像描述

如您所見,拐角處的邊界被切斷。

任何建議我做錯了什么?

像這樣嘗試:不要將cornerRadius設置為Button,而是使用內部視圖的疊加層:

編輯:如果您有按鈕的背景,您還需要將cornerRadius 應用於背景。

    Button(action: {
        print("sign up bin tapped")
    }) {
        Text("SIGN UP")
            .frame(minWidth: 0, maxWidth: .infinity)
            .font(.system(size: 18))
            .padding()
            .foregroundColor(.white)
            .overlay(
                RoundedRectangle(cornerRadius: 25)
                    .stroke(Color.white, lineWidth: 2)
        )
    }
    .background(Color.yellow) // If you have this
    .cornerRadius(25)         // You also need the cornerRadius here
    

為我工作。 讓我知道它是否有幫助!

更新了 Swift 5 和 iOS 13.4+ 與新聞狀態!

這些示例都不適用於同時具有深色和白色背景 colors 的按鈕,而且它們都沒有按 state 更新,所以我構建了這個您可以在下面看到的LargeButton視圖。 希望這會有所幫助,應該很容易使用!

示例照片

在此處輸入圖像描述

示例使用

// White button with green border.
LargeButton(title: "Invite a Friend", 
            backgroundColor: Color.white, 
            foregroundColor: Color.green) {
                        print("Hello World")
                    }

// Yellow button without a border
LargeButton(title: "Invite a Friend", 
            backgroundColor: Color.yellow) {
                        print("Hello World")
                    }

代碼

struct LargeButtonStyle: ButtonStyle {
    
    let backgroundColor: Color
    let foregroundColor: Color
    let isDisabled: Bool
    
    func makeBody(configuration: Self.Configuration) -> some View {
        let currentForegroundColor = isDisabled || configuration.isPressed ? foregroundColor.opacity(0.3) : foregroundColor
        return configuration.label
            .padding()
            .foregroundColor(currentForegroundColor)
            .background(isDisabled || configuration.isPressed ? backgroundColor.opacity(0.3) : backgroundColor)
            // This is the key part, we are using both an overlay as well as cornerRadius
            .cornerRadius(6)
            .overlay(
                RoundedRectangle(cornerRadius: 6)
                    .stroke(currentForegroundColor, lineWidth: 1)
        )
            .padding([.top, .bottom], 10)
            .font(Font.system(size: 19, weight: .semibold))
    }
}

struct LargeButton: View {
    
    private static let buttonHorizontalMargins: CGFloat = 20
    
    var backgroundColor: Color
    var foregroundColor: Color
    
    private let title: String
    private let action: () -> Void
    
    // It would be nice to make this into a binding.
    private let disabled: Bool
    
    init(title: String,
         disabled: Bool = false,
         backgroundColor: Color = Color.green,
         foregroundColor: Color = Color.white,
         action: @escaping () -> Void) {
        self.backgroundColor = backgroundColor
        self.foregroundColor = foregroundColor
        self.title = title
        self.action = action
        self.disabled = disabled
    }
    
    var body: some View {
        HStack {
            Spacer(minLength: LargeButton.buttonHorizontalMargins)
            Button(action:self.action) {
                Text(self.title)
                    .frame(maxWidth:.infinity)
            }
            .buttonStyle(LargeButtonStyle(backgroundColor: backgroundColor,
                                          foregroundColor: foregroundColor,
                                          isDisabled: disabled))
                .disabled(self.disabled)
            Spacer(minLength: LargeButton.buttonHorizontalMargins)
        }
        .frame(maxWidth:.infinity)
    }
}

iOS 15+ 中的官方.bordered修飾符支持

Button現在已經使用.buttonStyle(.bordered)修飾符獲得了邊框樣式支持。 我建議使用 Apple 為這些按鈕提供的圓角半徑,以獲得最佳的特定於平台的樣式。 我們可以將顏色更改為與系統 styles 的按鈕一致,並使用.tint修飾符為背景和文本着色:

Button("Add") { ... }
.buttonStyle(.bordered)
.tint(.green)

綠色色調按鈕

您可以使用.controlSize使色調顏色更加突出(更大膽)並使用.borderedProminent控制大小:

Button("food") { ... }
.tint(.red)
.controlSize(.small) // .large, .medium or .small
.buttonStyle(.borderedProminent)

小按鈕

您還可以在Button的父View上使用此修飾符,並在子Button中使用.accentColor切換較淺的配色方案:

ScrollView {
    LazyVStack {
        Button("Test Button 1") { ... }
        .buttonStyle(.borderedProminent)
        .keyboardShortcut(.defaultAction) // Tapping `Return` key actions this button

        Button("Test Button 2") { ... }
        .tint(.accentColor)
    }
}
.buttonStyle(.bordered)
.controlSize(.large)

大按鈕樣式

建議

Apple 出於某種原因不喜歡單線邊框按鈕,這就是為什么.border()修飾符在 Xcode 12 中被棄用的原因。通過此更改,我建議開發人員避免創建單線邊框按鈕,因為它們現在在 Apple 的人機界面指南。 在任何地方使用突出的按鈕也違反了 HIG。

額外注意:Apple 的.bordered樣式提供跨設備類型的標准平台樣式。 此外, Button動態響應暗模式並使用動態類型(本機可訪問性支持)縮放其大小。

Swift 5 & iOS 14 – 按下時邊框也會反應

struct PrimaryButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding(5)
            .foregroundColor(configuration.isPressed ? Color.red.opacity(0.5) : .red)
            .overlay(
                RoundedRectangle(cornerRadius: 8)
                    .stroke(configuration.isPressed ? Color.red.opacity(0.5) : .red, lineWidth: 1.5)
            )
     }
}

如何使用

Button("Hide") {
    print("tapped")
}.buttonStyle(PrimaryButtonStyle())

邊框在按下時也會做出反應

只需添加cornerRadius參數:

.border(Color.white, width: 2, cornerRadius: 25)

使用這個簡單的擴展

extension View {
    func border(_ color: Color, width: CGFloat, cornerRadius: CGFloat) -> some View {
        overlay(RoundedRectangle(cornerRadius: cornerRadius).stroke(color, lineWidth: width))
    }
}

預習

Xcode 11.4.1

                            Button(action: self.action) {
                                Text("Button Name")
                                    .font(.system(size: 15))
                                    .fontWeight(.bold)
                                    .foregroundColor(.white)
                                    .padding(10)
                                    .background(Color.darkGray)
                                    .cornerRadius(10)
                            }
                            .buttonStyle(PlainButtonStyle())

無需添加疊加層。 您可以用幀修飾符替換填充修飾符。 該操作是主體變量之外的非返回方法。

專門針對@MinonWeerasinghe:

Button(action: self.action) {
            Text("Button Name")
                .font(.system(size: 15))
                .fontWeight(.bold)
                .foregroundColor(.black)
                .padding(10)
                .background(RoundedRectangle(cornerRadius: 10).stroke().foregroundColor(Color.red))
                .cornerRadius(10)
        }
        .buttonStyle(PlainButtonStyle())

你可以試試這個:

var body: some View {
        ZStack {
            Color.green
            .edgesIgnoringSafeArea(.all)

            HStack {
            Button(action: {
                    print("sign up bin tapped")
            }){
                HStack {
                    Text("SIGN UP")
                        .font(.system(size: 18))
                    }
                .frame(minWidth: 0, maxWidth: 300)
                .padding()
                .foregroundColor(.white)
                .overlay(
                    RoundedRectangle(cornerRadius: 40)
                        .stroke(Color.white, lineWidth: 2)
                )

                }
            }
        }
    }

我也沒有將 maxWidth 設置為.infinity,因為這意味着按鈕將填充容器視圖的寬度。

結果將是:

在此處輸入圖像描述

希望能幫助到你:)

這對我有用

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"))

你應該使用膠囊。 這是內置在 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))
    }
}

在此處輸入圖像描述

要創建帶圓角的邊框,您可以繪制一個圓角矩形並覆蓋在按鈕上,如下所示:

  Button(action: {
        print("Hello button tapped!")
    }) {
        Text("Hello World")
            .fontWeight(.bold)
            .font(.title)
            .foregroundColor(.purple)
            .padding()
            .overlay(
                RoundedRectangle(cornerRadius: 20)
                    .stroke(Color.purple, lineWidth: 5)
            )
    }

在此處輸入圖像描述

Swift 5.6 版您可以使用按鈕屬性,例如

       Button(action: {
            //define action
        }) {
            Image(systemName: "arrow.triangle.2.circlepath.circle.fill")
                .imageScale(.large)
            Text("Restart")
                .font(.system(.title2))
        }
        .buttonStyle(.borderedProminent)
        .buttonBorderShape(.capsule)
        .controlSize(.large)

在此處輸入圖像描述

        .buttonBorderShape(.roundedRectangle) //change bordershape see below

在此處輸入圖像描述

        .buttonBorderShape(.roundedRectangle(radius: 4)) // see below

在此處輸入圖像描述

同樣,您可以更改buttonSytlecontrolSize

想知道如何使用顏色漸變和角半徑添加按鈕邊框這是如何..

  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)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM