<span style="color:#3333ff;">如果一個Button裏面帶有圖片,基本上我們用到有兩種情況,一種是文字在左圖片在右,一種是圖片在左文字在右,針對這兩種情況我們一般是可以設置UIButton的
setImageEdgeInsets屬性,但是這樣去改變有時候會很麻煩,所以我的入手點變爲重寫Button的方法。</span>
<span style="color:#ff0000;">一、圖片在文字左邊的情況:</span>
#define ButtonTitleFont [UIFont systemFontOfSize:14]
@implementation OKWMyButton
- (id)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
<span style="color:#009900;">//可根據自己的需要隨意調整</span>
self.titleLabel.textAlignment =NSTextAlignmentLeft;
self.titleLabel.font =ButtonTitleFont;
self.imageView.contentMode =UIViewContentModeScaleAspectFit;
}
returnself;
}
<span style="color:#009900;">//重寫父類UIButton的方法
//更具button的rect設定並返回文本label的rect</span>
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleW = contentRect.size.width-30;
CGFloat titleH = contentRect.size.height;
CGFloat titleX =30;
CGFloat titleY =0;
contentRect = (CGRect){{titleX,titleY},{titleW,titleH}};
return contentRect;
}
<span style="color:#009900;">//更具button的rect設定並返回UIImageView的rect</span>
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageW =20;
CGFloat imageH =20;
CGFloat imageX =5;
CGFloat imageY =12;
contentRect = (CGRect){{imageX,imageY},{imageW,imageH}};
return contentRect;
}
<span style="color:#ff0000;">二、圖片在文字右邊</span>
#define ButtonTitleFont [UIFont systemFontOfSize:14]
@implementation OKWMyImageRightButton
- (id)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
<span style="color:#009900;">//可根據自己的需要隨意調整</span>
self.titleLabel.textAlignment =NSTextAlignmentRight;
self.titleLabel.font =ButtonTitleFont;
self.imageView.contentMode =UIViewContentModeScaleAspectFit;
}
returnself;
}
<span style="color:#009900;">//重寫父類UIButton的方法
//更具button的rect設定並返回文本label的rect</span>
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleW = contentRect.size.width-24;
CGFloat titleH = contentRect.size.height;
CGFloat titleX =0;
CGFloat titleY =0;
contentRect = (CGRect){{titleX,titleY},{titleW,titleH}};
return contentRect;
}
<span style="color:#009900;">//更改button的rect設定並返回UIImageView的rect</span>
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageW =5;
CGFloat imageH =10;
CGFloat imageX = contentRect.size.width-24;
CGFloat imageY =15;
contentRect = (CGRect){{imageX,imageY},{imageW,imageH}};
return contentRect;
}
關於UIButton裏面帶有圖片的研究
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.