// 重写UIButton的titleRectForContentRect
-(CGRect)titleRectForContentRect:(CGRect)contentRect
{
#warning - 这里计算文字的size时,注意字体大小要要和实际的大小保持一致
CGSize titleSize = [self.currentTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18]} context:nil].size;
CGFloat imageW = self.currentImage.size.width;
CGFloat titleX = (self.frame.size.width - titleSize.width - imageW - 3) / 2;
CGFloat titleY = (self.frame.size.height - titleSize.height) / 2;
if (titleX < 0.0) {
titleX = 5;
}
CGFloat titleW = self.frame.size.width - imageW - 3;
CGFloat titleH = self.frame.size.height;
return CGRectMake(titleX, titleY, titleW, titleH);
}
// 重写UIButton的imageRectForContentRect
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGSize titleSize = [self.currentTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18]} context:nil].size;
CGFloat imageW = self.currentImage.size.width;
CGFloat imageH = self.currentImage.size.height;
CGFloat titleX = (self.frame.size.width - titleSize.width - imageW) / 2;
CGFloat imageX = titleX + titleSize.width + 3;
if ((imageX + self.currentImage.size.width + 5) > self.frame.size.width) {
imageX = self.frame.size.width - self.currentImage.size.width - 8;
}
CGFloat imageY = (self.frame.size.height - self.currentImage.size.height) / 2;
return CGRectMake(imageX, imageY, imageW, imageH);
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。