按钮图片文字位置设置

2018-10-08  本文已影响17人  6灰太狼9

btn默认图左字右

//将按钮设置为图片在上,文字在下
-(void)initButton:(UIButton*)btn{
    float  spacing = 10;//图片和文字的上下间距
    CGSize imageSize = btn.imageView.frame.size;
    CGSize titleSize = btn.titleLabel.frame.size;
    CGSize textSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : btn.titleLabel.font}];
    CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
    if (titleSize.width + 0.5 < frameSize.width) {
        titleSize.width = frameSize.width;
    }
    CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);
    btn.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, - imageSize.width, - (totalHeight - titleSize.height), 0);
    
}
//将按钮设置为图片在下,文字在上
-(void)initButton:(UIButton*)btn{
    float  spacing = 10;
    CGSize imageSize = btn.imageView.frame.size;
    CGSize titleSize = btn.titleLabel.frame.size;
    CGSize textSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : btn.titleLabel.font}];
    CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
    if (titleSize.width + 0.5 < frameSize.width) {
        titleSize.width = frameSize.width;
    }
    CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);

    btn.imageEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, - (totalHeight - imageSize.height), - titleSize.width);
    btn.titleEdgeInsets = UIEdgeInsetsMake(- (totalHeight - titleSize.height), - imageSize.width, 0, 0);


}
//将按钮设置为图片在右,文字在左
-(void)initButton:(UIButton*)btn{
    float  spacing = 10;
    CGSize imageSize = btn.imageView.frame.size;
    CGSize titleSize = btn.titleLabel.frame.size;
    CGSize textSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : btn.titleLabel.font}];
    CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
    if (titleSize.width + 0.5 < frameSize.width) {
        titleSize.width = frameSize.width;
    }
    CGFloat totalWidth = (imageSize.width + titleSize.width + spacing);
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, titleSize.width, 0, - titleSize.width);
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, -(totalWidth -titleSize.width), 0, (totalWidth -titleSize.width));
    
}

注意:

CGSize titleSize = btn.titleLabel.frame.size;
CGSize textSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : btn.titleLabel.font}];

这两个值不同,titleSize只跟btn的Frame相关。textSize跟titleLabel的字体文案相关。

上一篇下一篇

猜你喜欢

热点阅读