在开发中,我们经常会用到button这个控件,button上本身就可以单独设置图片和文字,但是要将图片和文字同时放置在button上,比如,图片在左边,标题在右边等布局,这样的button就稍微小麻烦一点了。如果直接将UIImageView和Label直接创建之后add在button之上,那么button就不可以点击了。因此,我常用的有两种方法:
1、继承UIButton并重写两个函数:
-(CGRect) imageRectForContentRect:(CGRect)contentRect ;
-(CGRect) titleRectForContentRect:(CGRect)contentRect;
这样的话可以Button为父坐标,在button上设置图片和文字的位置,这样使用起来比较方便一些
#import <UIKit/UIKit.h>
@interface BottomButton: UIButton
- (CGRect)imageRectForContentRect:(CGRect)contentRect;
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
@end
#import "BottomButton.h"
@implementation BottomButton
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
return CGRectMake(30, 9, kbuttonIconImageW, kbuttonIconImageH);//图片的位置大小
}
-(CGRect)titleRectForContentRect:(CGRect)contentRect
{
return CGRectMake(60, 9, kbuttonLabelW, kbuttonLabelH);//文本的位置大小
}
@end
2、使用UIButton中的三个对EdgeInsets的设置:ContentEdgeInsets、titleEdgeInsets、imageEdgeInsets
//给button添加image
[button setImage:[UIImage imageNamed:@"IconHome@2x.png"] forState:UIControlStateNormal];
//设置image在button上的位置(上top,左left,下bottom,右right)这里可以写负值,对上写-5,那么image就象上移动5个像素
button.imageEdgeInsets = UIEdgeInsetsMake(5,13,21,button.titleLabel.bounds.size.width);
//设置button的title
[button setTitle:@"首页" forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:16];
//设置title的字体居中
button.titleLabel.textAlignment = NSTextAlignmentCenter;
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//设置title在button被选中情况下为灰色字体
[button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
//设置title在button上的位置(上top,左left,下bottom,右right)
button.titleEdgeInsets = UIEdgeInsetsMake(71, -button.titleLabel.bounds.size.width-50, 0, 0);
// [button setContentEdgeInsets:UIEdgeInsetsMake(70, 0, 0, 0)];
//设置button的内容横向居中。。设置content是title和image一起变化
// button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[button addTarget:self action:@selector(tap) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
本人亲身体会,使用这种方法,调试图片和文字位置时,确实浪费不少时间。
附上本博主之前参考的博客地址:
http://www.tuicool.com/articles/bIvyYvQ
http://doc.okbase.net/willingYaTou/archive/38295.html
http://blog.csdn.net/ablongfei/article/details/44588007