Skip to content

Instantly share code, notes, and snippets.

@devraj
Last active March 28, 2019 00:55
Show Gist options
  • Save devraj/d53c696b035c1a530226b466079cb252 to your computer and use it in GitHub Desktop.
Save devraj/d53c696b035c1a530226b466079cb252 to your computer and use it in GitHub Desktop.
UIButton with Text Positioned under an image
import UIKit
// https://stackoverflow.com/questions/37915212/storyboard-positioning-text-below-image-inside-a-button/37915362
public extension UIButton
{
func alignTextUnderImage(spacing: CGFloat = 6.0)
{
if let image = self.imageView?.image
{
let imageSize: CGSize = image.size
self.titleEdgeInsets = UIEdgeInsets(top: spacing, left: -imageSize.width, bottom: -(imageSize.height), right: 0.0)
let labelString = NSString(string: self.titleLabel!.text!)
let titleSize = labelString.size(withAttributes: [NSAttributedString.Key.font: self.titleLabel!.font as Any])
self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0.0, bottom: 0.0, right: -titleSize.width)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment