Skip to content

Instantly share code, notes, and snippets.

@seankovacs
Created November 30, 2016 22:10
Show Gist options
  • Save seankovacs/c264b499359dfca8e20183c38650e613 to your computer and use it in GitHub Desktop.
Save seankovacs/c264b499359dfca8e20183c38650e613 to your computer and use it in GitHub Desktop.
Storyboard friendly UIButton with centered text and image
Adjusting the edge insets screws up the intrinsic size of the button, causing the hit area to be skewed.
// UICenteredButton.h
// Created by Sean Kovacs on 6/9/15.
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface UICenteredButton : UIButton
@end
// UICenteredButton.m
// Created by Sean Kovacs on 6/9/15.
// Copyright (c) 2015 InterBay Applications, LLC. All rights reserved.
#import "UICenteredButton.h"
const CGFloat kPadding = 5.0f;
@implementation UICenteredButton
- (void)prepareForInterfaceBuilder
{
[self applyDefaultCustomization];
}
- (void)setNeedsLayout
{
[super setNeedsLayout];
[self applyDefaultCustomization];
}
- (void)applyDefaultCustomization
{
CGSize imageSize = self.imageView.frame.size;
CGSize titleSize = [self.titleLabel.text sizeWithAttributes: @{NSFontAttributeName:self.titleLabel.font}];
CGFloat totalHeight = (imageSize.height + titleSize.height + kPadding);
self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height),
0.0f,
0.0f,
- titleSize.width);
self.titleEdgeInsets = UIEdgeInsetsMake(0.0f,
- imageSize.width,
- (totalHeight - titleSize.height),
0.0f);
}
- (CGSize) intrinsicContentSize
{
CGSize s = [super intrinsicContentSize];
return CGSizeMake(s.width + fabs(self.titleEdgeInsets.left) + fabs(self.titleEdgeInsets.right),
s.height + fabs(self.titleEdgeInsets.top) + fabs(self.titleEdgeInsets.bottom));
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment