在开发的过程当中常常会遇到须要在button中放置图片和文字,好比将图片放置在button左边,文字放置在右边。由于UIButton也是继承自UIView,所以能够像其它的view同样添加subView,ide
//建立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;
对于这个问题,建议采用以下方方:spa
继承UIButton并重写两个函数:code
-(CGRect) imageRectForContentRect:(CGRect)contentRect ;orm
-(CGRect) titleRectForContentRect:(CGRect)contentRect;blog
这两个函数能够设置图片和文字的大小和位置.继承
#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];