UIButton

  • 修改UIButton中文字和图片的位置
    • 重写下面两个方法(这里以把图片放到右边为例)
// 重写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);
}

你可能感兴趣的:(UIButton)