Skip to content

Instantly share code, notes, and snippets.

@fcaldarelli
Created October 29, 2016 09:37
Show Gist options
  • Save fcaldarelli/f676b6fb0f8f0c432aad694b1b855e8d to your computer and use it in GitHub Desktop.
Save fcaldarelli/f676b6fb0f8f0c432aad694b1b855e8d to your computer and use it in GitHub Desktop.
Center image and text in UIButton
- (void)centerImageTextInUIButton:(UIButton*)btn
{
// set custom font
UIFont *font = [UIFont fontWithName:@"SourceSansPro-Regular" size:12];
[btn.titleLabel setFont:font];
// the space between the image and text
CGFloat spacing = 6.0;
// lower the text and push it left so it appears centered
// below the image
CGSize imageSize = btn.imageView.image.size;
btn.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);
// raise the image and push it right so it appears centered
// above the text
CGSize titleSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: btn.titleLabel.font}];
btn.imageEdgeInsets = UIEdgeInsetsMake(- (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
// increase the content height to avoid clipping
CGFloat edgeOffset = fabsf(titleSize.height - imageSize.height) / 2.0;
btn.contentEdgeInsets = UIEdgeInsetsMake(edgeOffset, 0.0, edgeOffset, 0.0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment