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