UIButton設置圖片和文字

在開發的過程當中常常會遇到須要在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)contentRectorm

 -(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];
相關文章
相關標籤/搜索