Round 'em up - Dem corners of Views

I came across an article / tutorial today that talks about making UIImageView with rounded corners. The only problem that I see with that article is that though it uses Swift, it does so in a restrictive manner and in a not very Swift manner. So here is an attempt towards a better Swift implementation.
Here's the original code that sparked this off
import UIKit
    class ViewController: UIViewController {
        
        @IBOutlet weak var profile_picture: UIImageView!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Make image borders rounded
            profile_picture.layer.cornerRadius = 10
            profile_picture.clipsToBounds = true
            profile_picture.layer.borderWidth = 3
            profile_picture.layer.borderColor = UIColor.white.cgColor
        }
        
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        
    }

How to deal with this the Swift way?

The issue with the code above is that it works with just one specific view. What if we wanted this to be a generic way to create rounded corners for our views? After all, in an app there could be more than one view that needs rounded corners.

Attempt 1

The first way is to create a function, one that takes the view as a parameter and then rounds it's corners. Rather than doing anything fancy, we are simply wrapping this code in a function as
func roundedCorners(forView: UIView, radius: CGFloat, borderWidth: CGFloat, borderColor: CGColor, clip: Bool) {
        forView.layer.cornerRadius = radius
        forView.layer.borderWidth  = borderWidth
        forView.layer.borderColor  = borderColor
        forView.clipsToBounds      = clip
    }

and now you can simply call it by passing it the view and other details.

Attempt 2

The way to use a function is fine but you can try the amazing features of Swift, especially extensions.

extension UIView {
        func roundedCorners(radius: CGFloat, borderWidth: CGFloat, borderColor: CGColor, clip: Bool) {
            seld.layer.cornerRadius = radius
            self.layer.borderWidth  = borderWidth
            self.layer.borderColor  = borderColor
            self.clipsToBounds      = clip
        }
    }

Now each and every UIView and its subclasses like UIImageView will have the function roundedCorners available. You can simply use it like
let view = UIView()
    view.backgroundColor = UIColor.red
    view.roundedCorners(radius: 10, borderWidth: 3, borderColor: UIColor.white.cgColor, clip: true)

Summary

Well there you have it, you can add rounded corners to any view, even those with connections to IBOutlets



Comments

Popular Posts