iOS-UIButton设置图片和文字

在开发中,我们经常会用到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

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值