UIButton的image(不是backgroundImageView)和title是不重叠的, 但是使用backgroundImage又不够灵活. 这里是使用继承实现UIButton的image和title同时居中的方法.
继承UIButton, 在.m文件中写如下代码
#import "ZYCenterButton.h"
@implementation ZYCenterButton
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.titleLabel.textAlignment = NSTextAlignmentCenter;
}
return self;
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
CGRect frame = contentRect;
frame.origin.x = self.frame.size.width/2 - frame.size.width/2;
frame.origin.y = self.frame.size.height/2 - frame.size.height/2;
return frame;
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect {
CGRect frame = contentRect;
frame.origin.x = self.frame.size.width/2 - frame.size.width/2;
frame.origin.y = self.frame.size.height/2 - frame.size.height/2;
return frame;
}
@end
效果如下(和气泡没有半毛钱关系, 我只找到这张图好看点):
80A5D7D5-98E5-4D85-8701-C72A9FDD88FC.png