FabrizioCaldarelli
8/12/2015 - 3:40 PM

UIButton with scaled image and bottom text centered

UIButton with scaled image and bottom text centered

#import "ButtonWithImageAndBottomText.h"

@interface ButtonWithImageAndBottomText()

    @property (nonatomic, assign) float imageScaleFactor;

@end

@implementation ButtonWithImageAndBottomText

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)awakeFromNib
{
    self.imageScaleFactor = 0.6;
}

-(void)layoutSubviews {
    [super layoutSubviews];
    
    // Move the image to the top and center it horizontally
    CGRect imageFrame = self.imageView.frame;
    imageFrame.size = CGSizeMake(self.frame.size.width * self.imageScaleFactor, self.frame.size.height * self.imageScaleFactor);
    imageFrame.origin.y = 0;
    imageFrame.origin.x = (self.frame.size.width / 2) - (imageFrame.size.width / 2);
    self.imageView.frame = imageFrame;
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    // Adjust the label size to fit the text, and move it below the image
    CGRect titleLabelFrame = self.titleLabel.frame;
    
    CGRect labelRect = [self.titleLabel.text boundingRectWithSize:CGSizeMake(self.frame.size.width, CGFLOAT_MAX)
                                             options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                          attributes:@{NSFontAttributeName:self.titleLabel.font}
                                             context:nil];
    
    CGSize labelSize = labelRect.size;
    titleLabelFrame.size.width = labelSize.width;
    titleLabelFrame.size.height = labelSize.height;
    titleLabelFrame.origin.x = (self.frame.size.width / 2) - (labelSize.width / 2);
    titleLabelFrame.origin.y = self.bounds.size.height-labelSize.height;
    self.titleLabel.frame = titleLabelFrame;
    
}

@end