The easiest way to change text on UIButton with image and insets.

Dmitry Deplov
Simple Swift programming tips
3 min readJun 7, 2015

--

Photo by Tim Perry

Each of us loves to make something thats looks nice and done easily. So, here some help for you, if you find yourself in trouble with UIButton.

This article is about setting new title text to UIButton, that contains title and image lined up using UIButton’s insets.

I love to make things in Interface Builder(IB), because this is reduce the amount of code you need to write and debug. First, we add image and title text to the button. Next, we set up insets. You can do this by different ways. I made some space by adding left and right insets to Content Edge. Then I add some insets to title and to image, to make some space between each other. I want to mention, that I use autolayout, but I think most of the developers use it already. Here is what we got:

Our nicely designed button in IB.

When we need to change our title, but we don’t want to destroy our neat, manually setted spacing to title and button edges.

Here is what I suggest you to do. You need to set width constraint for your button and add IBOutlet for that constraint to your View Controller. I made an extension for UIButton for setting new title, that makes this process very easy.

extension UIButton {
func selectedButton(title:String, iconName: String, widthConstraints: NSLayoutConstraint){
self.backgroundColor = UIColor(red: 0, green: 118/255, blue: 254/255, alpha: 1)
self.setTitle(title, for: .normal)
self.setTitle(title, for: .highlighted)
self.setTitleColor(UIColor.white, for: .normal)
self.setTitleColor(UIColor.white, for: .highlighted)
self.setImage(UIImage(named: iconName), for: .normal)
self.setImage(UIImage(named: iconName), for: .highlighted)
let imageWidth = self.imageView!.frame.width
let textWidth = (title as NSString).size(attributes:[
NSFontAttributeName:self.titleLabel!.font!]).width
let width = textWidth + imageWidth + 24
//24 - the sum of your insets from left and right
widthConstraints.constant = width
self.layoutIfNeeded()
}
}

The function require 3 parameters: new title for button, image (in case you want to change it) and width constraint of the button.

Nice transformation. It’s can be animated also!

When you call the function, in my case, it will set backgroundColor of the button, title, color of the title text and icon for Normal and Highlighted states. Then it will calculate width of the new title along with image width and insets and set this sum to the width constraint. You will see these buttons in our new to-do app Taskler.

Final result with some added functionality

You can extend the function to customise it for your needs. It’s comfortable to take this part of code out of the View Controller and left only the method call when you need it.

--

--