Skip to content

Instantly share code, notes, and snippets.

@gonelf
Created May 27, 2015 14:55
Show Gist options
  • Save gonelf/7431d65f43e6f986606f to your computer and use it in GitHub Desktop.
Save gonelf/7431d65f43e6f986606f to your computer and use it in GitHub Desktop.
UIButton center text with image (extension)
import UIKit
extension UIButton {
func centerTextWithImage (margin:CGFloat) {
var width = self.frame.width
var imgWidth = self.imageView!.frame.width as CGFloat
var txt = self.titleLabel!.text
var textSize = self.titleLabel!.sizeOfString(txt!, height: Double(self.frame.height)) as CGSize
var spacing = (width - (imgWidth + textSize.width)) / 2
self.imageEdgeInsets = UIEdgeInsetsMake(0, margin, 0, spacing);
self.titleEdgeInsets = UIEdgeInsetsMake(0, spacing + (margin/2), 0, 0);
}
}
@Rashesh-Bosamiya
Copy link

Please add extension for sizeOfString.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment