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!

Swift Tips #1: Extra padding problem on UITextView?

Sometimes when you integrate a design, you need things to be square, everything aligned: buttons, title, images, textView… But wait, what’s that extra padding on the UITextView? You may have tried to print the contentOffset or contentInset without success. That’s not it. However, all your problems can be solved in one line, and here it is: // magic line for a UITextView named textView textView.textContainer.lineFragmentPadding = 0 I wouldn’t call it exactly straight forward, so this is a memo for me and tip for you :)