Skip to content

Instantly share code, notes, and snippets.

@r3econ
Last active May 14, 2020 01:30
Show Gist options
  • Save r3econ/9738515 to your computer and use it in GitHub Desktop.
Save r3econ/9738515 to your computer and use it in GitHub Desktop.
UIButton category for centering title label and image vertically. The text label is placed below the image.
@interface UIButton (VerticalLayout)
- (void)centerVerticallyWithPadding:(float)padding;
- (void)centerVertically;
@end
#import "UIButton+VerticalLayout.h"
@implementation UIButton (VerticalLayout)
- (void)centerVerticallyWithPadding:(float)padding
{
CGSize imageSize = self.imageView.frame.size;
CGSize titleSize = self.titleLabel.frame.size;
CGFloat totalHeight = (imageSize.height + titleSize.height + padding);
self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height),
0.0f,
0.0f,
- titleSize.width);
self.titleEdgeInsets = UIEdgeInsetsMake(0.0f,
- imageSize.width,
- (totalHeight - titleSize.height),
0.0f);
}
- (void)centerVertically
{
const CGFloat kDefaultPadding = 6.0f;
[self centerVerticallyWithPadding:kDefaultPadding];
}
@end
@chadkouse
Copy link

as indicated here (where I assume this came from) the calculation of the titleSize doesn't work properly for custom fonts / sizes.

This works and is updated for ios7+

CGSize titleSize = [self.titleLabel.text sizeWithAttributes: @{NSFontAttributeName:self.titleLabel.font}];

@trant
Copy link

trant commented Nov 27, 2014

If you change the font of the titleLabel this won't work. The image does not center properly for some reason

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