[IOS](转)带文字图片(一)
转自:http://blog.csdn.net/u011462377/article/details/48595485
//创建一个button
UIButton *btn = [[UIButtonalloc]init];
[self.viewaddSubview:btn];
btn.frame =CGRectMake(100,200,90,90);
btn.backgroundColor = [UIColorgrayColor];
//添加图片
[btn setImage:[UIImageimageNamed:@"tab_0"]forState:UIControlStateNormal];
//添加文字
[btn setTitle:@"首页"forState:UIControlStateNormal];
// //设置文字的大小
btn.titleLabel.font = [UIFontsystemFontOfSize:16];
//为了能更好的显示图片和文字的位置我们设置一下图片和文字的背景颜色
btn.titleLabel.backgroundColor = [UIColorpurpleColor];
btn.imageView.backgroundColor = [UIColorcyanColor];
btn.imageEdgeInsets =UIEdgeInsetsMake(0,0,0,0);
移动前
imageView:{{14, 30}, {30, 30}}
移动后:
imageView:{{14, 30}, {30, 30}}
得出结论 全部设置为0 不做任何的移动
在设置button内部控件的对齐方式后,在设置内边距
btn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
//UIControlContentHorizontalAlignmentLeft水平左对齐
btn.contentVerticalAlignment =UIControlContentVerticalAlignmentTop;
//UIControlContentVerticalAlignmentTop垂直上对齐
NSLog(@"对齐后的imageView%@",NSStringFromCGRect(btn.imageView.frame));
NSLog(@"对齐后的titleLabel%@",NSStringFromCGRect(btn.titleLabel.frame));
btn.imageEdgeInsets =UIEdgeInsetsMake(40,0,0,0);
移动后imageView:{{0, 40}, {30, 30}}
此时我们可以改变左内距的值
btn.imageEdgeInsets =UIEdgeInsetsMake(40,10,0,0);
移动后imageView:{{10, 40}, {30, 30}}
结论:1.必须设置一种对其方式,那么该方向的移动的距离才为我们设置的值
2.因此我们如果想移动button内部的控件先改变其对其方式,在进行移动。
对button内部控件进行移动
//1.使imageView居中
//获取imageView中的宽度和高度
CGFloat imageW = btn.imageView.frame.size.width;
CGFloat imageH = btn.imageView.frame.size.height;
//获取titleLabel的宽度
CGFloat labelW = btn.titleLabel.frame.size.width;
CGFloat labelH = btn.titleLabel.frame.size.height;
//计算移动距离
CGFloat imageDistance = (btn.frame.size.width - imageW) * 0.5;
//设置上内距
CGFloat imageTop = (btn.frame.size.height - imageH - labelH) * 0.5;
//进行移动
btn.imageEdgeInsets = UIEdgeInsetsMake(imageTop, imageDistance, 0, 0);
NSLog(@"移动后的imageView%@",NSStringFromCGRect(btn.imageView.frame));
移动后的imageView{{30, 20}, {30, 30}}
这时我们发现imageView的frame值相对于对齐后确实发生了改变//使titleLabel居于imageView的正下方且居中
//获取titleLabel的宽度
CGFloat labelW = btn.titleLabel.frame.size.width;
//计算移动距离
CGFloat labelDistance = - imageW + (btn.frame.size.width - labelW) *0.5 ;
//上内距
CGFloat labelTop = imageTop + imageH;
btn.titleEdgeInsets =UIEdgeInsetsMake(labelTop, labelDistance,0,0);
NSLog(@"移动后的titleLabel%@",NSStringFromCGRect(btn.titleLabel.frame));
移动后的titleLabel{{30, 0}, {32, 19.5}}
此时我们发现移动后的titleLabelframe值和对齐后的frame值相同