图片文字居中上下排列的UIButton

简单思路:

layoutSubviews:的时候获取当button的frame, 然后通过直接设置imageViewtitleLabelframe来实现.

ASCenterButton.h

#import <UIKit/UIKit.h>

/**
 *  这个子类可以让UIButton的imageView和titleLabel垂直居中
 */
@interface ASCenterButton : UIButton

/**
 *  imageView和titleLabel的垂直距离,默认为2.0f
 */
@property (nonatomic, readwrite, assign) CGFloat spacing;

@end

ASCenterButton.m

#import "ASCenterButton.h"

@implementation ASCenterButton

- (void)layoutSubviews{
    [super layoutSubviews];

    [self.titleLabel sizeToFit];

    CGSize titleLabelSize = self.titleLabel.frame.size;

    CGRect buttonFrame = self.frame;

    CGFloat spacing = 2.0f;

    if (self.spacing > 0){
        spacing = ceilf(self.spacing);
    }

    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.imageView.frame = CGRectMake(0, 0, buttonFrame.size.width, buttonFrame.size.height - titleLabelSize.height - spacing);

    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.frame = CGRectMake(0, buttonFrame.size.height - titleLabelSize.height, buttonFrame.size.width, titleLabelSize.height);
}

@end

标签:none