Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(???)
like image 250
TheNeil Avatar asked Nov 24 '19 02:11

TheNeil


People also ask

How do you make a view rounded in SwiftUI?

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.

How do you round the corners of a view?

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 .

How do you use corner radius to view in Swift?

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.


2 Answers

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.

like image 191
d9rad Avatar answered Oct 08 '22 04:10

d9rad


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

like image 27
Bartosz Avatar answered Oct 08 '22 03:10

Bartosz