iOS经典讲解之UIButton改变图片和文字的位置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Loving_iOS/article/details/52412734

作者:刘新林

转载请标明出处:http://blog.csdn.net/loving_ios/article/details/52412734

UIButton的image和titleLabel是靠在一起居中显示的,默认image在左,titleLabel在右,但是有些情况要求两者交换位置显示,可以通过

@property(nonatomic)          UIEdgeInsets imageEdgeInsets;                // default is UIEdgeInsetsZero
@property(nonatomic)          UIEdgeInsets titleEdgeInsets;                // default is UIEdgeInsetsZero
这两个属性来设置。

 UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 20, 100, 30);
    [btn setTitle:@"测试" forState:(UIControlStateNormal)];
    [btn setImage:img forState:(UIControlStateNormal)];
    btn.adjustsImageWhenHighlighted = NO;
    [btn setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    btn.backgroundColor = [UIColor blueColor];
    [self.view addSubview:btn];
此时默认显示的样式如图:


如果设置其位置:通过添加代码

 CGFloat imgWidth = btn.imageView.bounds.size.width;
 CGFloat labWidth = btn.titleLabel.bounds.size.width;
 [btn setImageEdgeInsets:UIEdgeInsetsMake(0, labWidth, 0, -labWidth)];
 [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgWidth, 0, imgWidth)];
其样式改为:


实现了图片和文字的位置交换。

道理很简单,通过调节其偏移量来解决,image相当于左边偏移了label的宽度距离,右边相应减少偏移label的距离,titleLabel则相反。


猜你喜欢

转载自blog.csdn.net/Loving_iOS/article/details/52412734