How to implement rounded corners for buttons in SwiftUI

Normally when implementing buttons in iOS, which needs rounded corners, we use the corner radius API to round the corners. In order to do this, you would need to calculate the height and then divide by a number you deem suitable. This is not always a suitable choice, since you would always need to fetch the height and estimate the denominator.

The newer and easier way to do this in SwiftUI, is to use the Capsule API. https://developer.apple.com/documentation/swiftui/capsule

A capsule shape is equivalent to a rounded rectangle where the corner radius is chosen as half the length of the rectangle’s smallest edge.

This API will automatically round the corners for you. The implementation is as shown below:

import SwiftUI

struct ContentView: View {
    var body: some View {
		VStack {
			HStack {
				Button(action: {
					print("This is a rounded button")
				}) {
					HStack() {
						Image(systemName: "pencil")
						Text("This is a rounded button")
					}
				}
				.buttonStyle(ButtonStyling(type: .heavy))
			}
		}
    }
}

public enum ButtonType {
	case light
	case italic
	case heavy
}

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


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *