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(???)
Any SwiftUI view can have its corners rounded using the cornerRadius() modifier. This takes a simple value in points that controls how pronounced the rounding should be.
You can give it round corners by changing the cornerRadius property of the view's layer . and smaller values give less rounded corners. Both clipsToBounds and masksToBounds are equivalent. It is just that the first is used with UIView and the second is used with CALayer .
Whenever you want to apply corner radius to UIView, make sure you call yourUIView. layoutIfNeeded() before calling cornerRadius . Otherwise, it will return the default value for UIView's height and width (1000.0) which will probably make your View disappear.
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.
You need to define it as a square and then put rounding on corners, like this:
Button(action: {
// ...
}) {
Text("I'm a Button")
.frame(width:150, height:150)
.background(Color.red)
.cornerRadius(.infinity)
}
PS. Added some background color for visibility
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With