swiftuicornerradius

SwiftUI: How to Get a View with Perfectly Rounded Corners


With UIKit, it's possible to give a control (e.g. a button) perfectly rounded corners (resulting in a circle on each side) by using this approach:

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

How does one achieve the same result with a SwiftUI view?

Because the views are defined more on the fly, I'm not sure how it would be possible to reference that frame size unless it's being set manually (which isn't the desire here).

Button(action: {
    // ...
}) {
    Text("I'm a Button")
}
.cornerRadius(???)

Solution

  • Another solution to this is to use shapes, in this case the Capsule shape, and use the clipShape modifier

    Taking the example already mentioned, it would be like this:

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

    The padding in there can be adjusted so that your view looks how you want it to. The point it that capsule will always have the ends perfectly rounded. In this case I didn't want the text to be too close to the rounded edges, so I applied some padding to the sides.

    A note to remember is that in SwiftUI the order the modifiers are applied in is very important.