// 重寫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);
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者