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];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM