第一種方法
首先獲取button上的titleLabel和imageView的寬和高,
imageView的寬高:
CGFloat imageWith = self.imageView.frame.size.width;
CGFloat imageHeight = self.imageView.frame.size.height;
當(dāng)然也可以通過這種方法獲取imageView的大小
CGFloat imageWidth = CGImageGetWidth([UIImage imageNamed:@"driving"].CGImage);
CGFloat imageHeight = CGImageGetHeight([UIImage imageNamed:@"driving"].CGImage);
不過需要注意的是需要辨別獲取的圖片是一倍圖,還是二倍圖亦或者三倍圖,然后用imageWidth和imageHeigt除以倍數(shù)
titleLabel的寬高:
CGFloat labelWidth = 0.0;
CGFloat labelHeight = 0.0;
if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
// 由于iOS8中titleLabel的size為0矾瑰,用下面的這種設(shè)置
labelWidth = self.titleLabel.intrinsicContentSize.width;
labelHeight = self.titleLabel.intrinsicContentSize.height;
} else {
labelWidth = self.titleLabel.frame.size.width;
labelHeight = self.titleLabel.frame.size.height;
}
然后設(shè)置button的imageEdgeInsets和labelEdgeInsets屬性
1.image在上,label在下
imageEdgeInsets = UIEdgeInsetsMake(-labelHeight-space/2.0, 0, 0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight-space/2.0, 0);
2.image在左,label在右
imageEdgeInsets = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(0, space/2.0, 0, -space/2.0);
3.image在下,label在上
imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space/2.0, -imageWith, 0, 0);
4.image在右,label在左
imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+space/2.0, 0, -labelWidth-space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith-space/2.0, 0, imageWith+space/2.0);
第二種
通過自定義button,重寫button的以下兩個方法
-(CGRect)titleRectForContentRect:(CGRect)contentRect;
-(CGRect)imageRectForContentRect:(CGRect)contentRect;
這里面你可以隨意設(shè)置titleLabel和imageView的位置
第三種
創(chuàng)建Button的時候使用UIButton *selectedButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 100, 100, 30)];來創(chuàng)建,然后把你需要添加的titleLabel或者imageView作為子視圖添加到button上,但是蘋果官方更推薦使用buttonWithType,因為這個是唯一一個設(shè)置buttonType的地方,并且這個方法正在MRC中可以自動釋放button,而initWithFrame需要手動釋放.