UIButton设置图片和文字

在开发的过程中经常会遇到需要在button中放置图片和文字,比如将图片放置在button左边,文字放置在右边。因为UIButton也是继承自UIView,因此可以像其它的view一样添加subView,

//创建button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 创建imageview
UIImage *image = [UIImage imageNamed:@"yourImage.png"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(/*frame*/)];
[imageView setImage:image];
// 创建label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(/*frame*/)];
[label setText:@"Your title"];
// 添加到button中
[button addSubview:label];
[button addSubview:imageView];

这种方法的好处是简单明了,但是其实在UIButton中已经包含了UIImageView,我们不需要在自己添加该imageView的。也可以采用如下的方法,但是该方法的在调整UI时比较不方便:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = buttonRect;
[button setTitle:@"title" forState:UIControlStateNormal];
[button setImage:buttonImage forState:UIControlStateNormal];
button.imageEdgeInsets = UIEdgeInsetsMake(0.0, WIDTH(button.titleLabel) + 10.0, 0.0, 0.0);
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

对于这个问题,建议采用如下方方:

继承UIButton并重写两个函数:

-(CGRect) imageRectForContentRect:(CGRect)contentRect

 -(CGRect) titleRectForContentRect:(CGRect)contentRect;

这两个函数可以设置图片和文字的大小和位置.

#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
//use ... self.forwardBtn
= [[BottomButton alloc] initWithFrame:CGRectMake(5,5 ,BottomButtonWidth ,BottomButtonHeight)]; [self.forwardBtn addTarget:self action:@selector(forwardButtonUpInsideAction) forControlEvents:UIControlEventTouchUpInside]; [self.forwardBtn setImage:[UIImage imageNamed:@"Forward.png"] forState:UIControlStateNormal];
[self.forwardBtn setImage:[UIImage imageNamed:
@"Forward_select.png"] forState:UIControlStateHighlighted]; [self.forwardBtn setTitleColor:labelFontColor forState:UIControlStateNormal]; [self.forwardBtn setTitleColor:RGBCOLOR(255, 160, 31) forState:UIControlStateHighlighted]; [self.forwardBtn setTitle:@"转发" forState:UIControlStateNormal ]; [self.forwardBtn.titleLabel setFont: [UIFont systemFontOfSize: BottomFontSize]]; [self addSubview:self.forwardBtn];

 

转载于:https://www.cnblogs.com/hello-LJ/p/4000669.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值