Apple Swift Logo

Swift Tips #2: setBorder Extension

Happy New Year! This is my first post of 2016, so I would like to thank you all for reading my blog and to wish you a very Happy New Year. May this year be as bug free as possible in your apps as well as in your life!

As a New Year gift, I’d like to share with you a little something that I’m using all the time: my setBorder Extension. It is the first member of my “Extensions essentials”.

When I integrate a design or debug something, I want to see quickly where my elements are, so I set a border to the ones I’d like to see. An old web habit perhaps, but I find it very useful.

Without further ado, here comes the code:

extension UIView {
    
    func setBorder(color: UIColor, width: CGFloat = 1.0) {
        self.layer.borderColor = color.CGColor
        self.layer.borderWidth = width
    }
}

You can place it wherever you want in the code. Personally, I like to create an Extension.swift file at the root of my project and put all my extensions there. As it is an extension of UIView, it works on all kinds of views: UIView, UIImage, UILabel, UITableView, UICollectionViewCell, …

To use the setBorder extension, it’s pretty easy:

myImage.setBorder(UIColor.redColor()) // red border with default width
myTable.setBorder(UIColor.blueColor(), width: 5) // large blue border

Obviously, you can customize it and unleash the power of the border by adding a default color value, or passing hexadecimal colors (I combined it with SwiftHEXColors on a project, it works beautifully!).

Happy coding!

Leave a Comment

You want to leave a comment? Sweet! Please do so, but keep in mind that all comments are moderated and rel="nofollow" is in use. So no fake comment or advertisement will be approved. And don't worry, your email address won't be published. Thanks!

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>