1>众所周知,在给系统的Button设置文字和image的时候(非背景颜色),系统默认是左边图片,右边文字,可现在需求是,左边是文字右边是图片.那么我们如何实现这一效果呢?
button有一个我们很少用的两个属性,分别是imageEdgeInsets和titleEdgeInsets,这两个属性就是分别设置图片和文字的距上下左右的距离,我们可以这样设置
addressBtn.imageEdgeInsets=UIEdgeInsetsMake(0, addressBtn.titleLabel.w,0, -addressBtn.titleLabel.w);
addressBtn.titleEdgeInsets=UIEdgeInsetsMake(0, -addressBtn.imageView.w,0, addressBtn.imageView.w);
最终笔者是写了一个UIImage+scale的分类解决了,
.h文件
import
@interfaceUIImage (scale)
-(UIImage*)scaleToSize:(CGSize)size;
@end
.m文件
import"UIImage+scale.h"
@implementationUIImage (scale)
-(UIImage*)scaleToSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
[selfdrawInRect:CGRectMake(0,0, size.width, size.height)];
UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnscaledImage;
}
@end
代码的使用:
[addressBtn setTitle:@"北京"forState:UIControlStateNormal];
UIImage* image1 = [UIImageimageNamed:@"weizhi"];
[addressBtn setImage:[image1 scaleToSize:CGSizeMake(9.5,13.0)]forState:UIControlStateNormal];
最终达成的效果为: