A Comprehensive Guide to Creating Rounded Border Buttons in Swift

Nov 20, 2025 · Programming · 15 views · 7.8

Keywords: Swift | UIButton | Rounded Border | CALayer | SwiftUI

Abstract: This article provides a detailed exploration of methods to add customizable rounded borders to buttons in Swift, covering UIKit's CALayer properties for basic border styling and SwiftUI's built-in and custom styles for transparent border buttons. Step-by-step code examples illustrate how to control border color, width, and corner radius, with comparisons between UIKit and SwiftUI frameworks.

Introduction

In iOS app development, buttons are central to user interaction. Adding rounded borders to buttons not only enhances visual appeal but also improves user experience. This article, based on the Swift programming language, thoroughly explains how to create customizable rounded borders for buttons, covering implementations in both UIKit and SwiftUI frameworks.

Creating Rounded Border Buttons with UIKit

In the UIKit framework, the border style of a UIButton is primarily configured through CALayer properties. CALayer, part of the Core Animation framework, handles the visual presentation of views, including effects like borders, shadows, and corners.

The following code demonstrates how to set a rounded border for a UIButton instance:

button.backgroundColor = .clear
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor

In this code, the button's background color is first set to clear, ensuring only the border is visible without any fill. Then, the cornerRadius property sets the corner radius to 5 points, creating smooth curves at the button's corners. The borderWidth property defines the border width as 1 point, and borderColor specifies the border color as black. Note that borderColor requires a CGColor type, hence the conversion via UIColor.black.cgColor.

This approach allows developers to flexibly adjust the border style. For example, to change the border color to red, simply modify borderColor to UIColor.red.cgColor; to increase the corner radius to 10 points, set cornerRadius to 10. This CALayer-based implementation is widely applicable in UIKit and compatible with multiple iOS versions.

Implementing Border Buttons in SwiftUI

SwiftUI, Apple's declarative UI framework, offers a more concise way to create bordered buttons. In iOS 15 and later, SwiftUI introduces built-in bordered button styles that streamline development.

Using Built-in Button Styles

SwiftUI provides .bordered and .borderedProminent button styles, the former creating a transparent button with a border, and the latter adding a background fill. The following code example illustrates the use of these styles:

VStack {
    Button("Bordered Button") {
        // Button action
    }
    .buttonStyle(.bordered)
    
    Button("Bordered Prominent Button") {
        // Button action
    }
    .buttonStyle(.borderedProminent)
}
.font(.title)

By applying styles with the .buttonStyle modifier, developers can quickly obtain standardized bordered buttons. Additionally, the .tint modifier allows customization of border and text colors, such as setting it to pink:

.tint(.pink)

The corner shape can be adjusted with .buttonBorderShape, supporting capsule shapes (.capsule) or custom rounded rectangles (e.g., .roundedRectangle(radius: 8)), enabling precise control over the border's roundness.

Custom Transparent Border Buttons

For border buttons with transparent backgrounds (similar to "ghost buttons"), SwiftUI lacks a direct built-in style but can be achieved by combining modifiers. The following code creates a transparent border button:

Button {
    // Button action
} label: {
    Text("Ghost Button")
        .padding()
        .foregroundColor(.pink)
        .background(
            RoundedRectangle(
                cornerRadius: 20,
                style: .continuous
            )
            .stroke(.pink, lineWidth: 2)
        )
}

In this implementation, RoundedRectangle defines the button's shape, with its cornerRadius parameter setting the corner radius to 20 points. The .stroke modifier adds the border, specifying the color as pink and line width as 2 points. foregroundColor sets the text color, while padding ensures adequate spacing between the text and border. This method is suitable for versions before iOS 15 or scenarios requiring high customization.

Creating Reusable Button Styles

To enhance code reusability, custom button styles can be defined. The following example creates a style named GhostButtonStyle based on the transparent border button:

struct GhostButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding()
            .foregroundStyle(.tint)
            .background(
                RoundedRectangle(
                    cornerRadius: 20,
                    style: .continuous
                )
                .stroke(.tint, lineWidth: 2)
            )
    }
}

// Extension for ease of use
extension ButtonStyle where Self == GhostButtonStyle {
    static var ghost: Self {
        return .init()
    }
}

After definition, this style can be applied via .buttonStyle(.ghost) and dynamically adjusted with .tint. This abstraction makes button styles easy to maintain and consistent across the app.

Comparative Analysis of UIKit and SwiftUI

When implementing rounded border buttons, UIKit and SwiftUI each have their strengths. UIKit, based on CALayer property settings, suits traditional imperative programming models, offering fine-grained control but with more verbose code. For instance, adjusting border color requires direct modification of borderColor, and corner radius is set numerically.

SwiftUI employs a declarative syntax, resulting in cleaner code, with built-in styles reducing boilerplate. For example, using the .bordered style requires only one modifier, while custom styles are achieved through view composition. However, SwiftUI has version requirements (e.g., built-in styles need iOS 15+), which may necessitate fallbacks in older projects.

In terms of performance, UIKit's CALayer operations are generally more efficient due to direct interaction with Core Animation; SwiftUI's declarative updates might involve more view redraws, but differences are minimal with Apple's optimizations. The choice of framework should consider project needs, team familiarity, and target iOS versions.

Practical Tips and Common Issues

In practical development, when creating rounded border buttons, several points should be noted: First, ensure sufficient contrast between border color and background for accessibility. Second, in UIKit, when setting cornerRadius, dynamically adjust the radius if button sizes change to avoid visual inconsistencies.

Common issues include borders not appearing or incorrect colors. In UIKit, this is often due to unset borderWidth or incorrect borderColor types (e.g., using UIColor instead of CGColor). In SwiftUI, if borders do not show, check if the .stroke modifier is correctly applied or if the view hierarchy is overlapped.

For cross-version compatibility, it is advisable to provide fallback solutions in SwiftUI projects for older iOS versions, such as using custom styles instead of built-in ones. In team collaborations, defining a unified button style library can improve consistency.

Conclusion

This article comprehensively explores methods for creating rounded border buttons in Swift, from the basics of UIKit's CALayer to advanced styles in SwiftUI. Through code examples and comparative analysis, it demonstrates how to achieve customizable border colors, widths, and corner radii. Whether leveraging UIKit's detailed control or SwiftUI's declarative convenience, developers can choose the appropriate solution based on project requirements. Mastering these techniques aids in building aesthetically pleasing and functionally robust iOS app interfaces.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.