smooth rounded corners in swift

Viewed 10946

How can I create a UIButton with rounded corners that are smooth? The standard apple rounded corners are much nicer than the standard rounded corners. If I design a button in sketch, I can toggle "smooth corners" which toggles the corners of a shape from Apple rounded corners (smooth) to standard rounded corners.

Here is a comparison:

enter image description here

How can I toggle this in swift?

showContentButton.layer.cornerRadius = 20 rounds the corners, however, I don't really know if this rounded corners are "smooth corners" or "standard rounded corners". And I don't know how to toggle this. Any ideas?

4 Answers

Prior to iOS 13

To get that effect you can use UIBezierPath

Smooth corners

Edit: Usage in UIView

class MyView: UIView {

    let myButton UIButton = UIButton()

    override func layoutSubviews() {
        super.layoutSubviews()

        // your roundPath code here
    }

}

Edit 2:

Use this approach for rounding specific corners:

let roundPath = UIBezierPath(
    roundedRect: bounds,
    byRoundingCorners: [.topLeft, .topRight],
    cornerRadii: CGSize(width: 10, height: 10)
)

Source

Just use this extension

extension CALayer {

   func roundCorners(radius: CGFloat) {
       let roundPath = UIBezierPath(
           roundedRect: self.bounds,
           cornerRadius: radius)
       let maskLayer = CAShapeLayer()
       maskLayer.path = roundPath.cgPath
       self.mask = maskLayer
   }

}

and use it like this

cell.layer.roundCorners(radius: 18)

For SwiftUI, you can try this:

.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))

Example:

Rectangle()
    .clipShape(RoundedRectangle(cornerRadius: 24, style: .continuous))
    .padding()

or use extension:

extension View {
    func smoothCornerRadius(_ x: CGFloat) -> some View {
        return self
            .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
    }
}

Result here

Related