iOS調整按紐圖片文字title位置的代碼
自定義一個button,要調整 button中的image(注意,不是backgroundImage) 和 title 文字的位置,只需要重寫 Button類獨對應的兩個方法即可:
首先,我們來創建一個 SuperButton繼承自 UIButton
//
// SuperButton.h
// SuperButton #import <UIKit/UIKit.h>@interface SuperButton : UIButton @end </pre>
實現文件
// // SuperButton.m // SuperButton // // #import "SuperButton.h" #import "UtilsFunctions.h" @interface SuperButton () { CGRect boundingRect; } @end @implementation SuperButton //自定義的初始化方法 - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self setTitle:@"項目介紹" forState:UIControlStateNormal]; [self.titleLabel setFont:[UIFont boldSystemFontOfSize:font]]; [self setBackgroundImage:[UIImage imageNamed:@"cpxq_shang@3x.png"] forState:UIControlStateNormal]; [self setImage:[UIImage imageNamed:@"cpxq_jiantou2@3x.png"] forState:UIControlStateNormal]; boundingRect=[self.titleLabel.text boundingRectWithSize:CGSizeMake(320,font) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil]; } return self; }
1.重寫方法,改變 圖片的位置 在 titleRect..方法后執行 - (CGRect)imageRectForContentRect:(CGRect)contentRect { CGFloat imageX=self.frame.size.width/2+boundingRect.size.width/2; UIScreen *s=[UIScreen mainScreen]; CGRect rect=s.bounds; CGFloat imageY=contentRect.origin.y+14; CGFloat width=24; CGFloat height=24; return CGRectMake(imageX, imageY, width, height); } 2.改變title文字的位置,構造title的矩形即可 - (CGRect)titleRectForContentRect:(CGRect)contentRect { CGFloat imageX=(self.frame.size.width-boundingRect.size.width)/2; CGFloat imageY=contentRect.origin.y+10; CGFloat width=220; CGFloat height=25; return CGRectMake(imageX, imageY, width, height); } @end
我們只要重寫 上述的兩個方法,就可以實現對 button按鈕中的圖片和文字的位置的調整注意:
1.ios7和ios8系統上 上述兩個方法 運行的次數會有差異,可以設置標志位,或者自定義一個 button(不要集成button)2.代碼是經過刪減的,大家關鍵是重寫上面的兩個方法,重新繪制矩形,即可
本文由用戶 gcd8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!