標籤:ios 按鈕圖片文字位置調整 button調整image位置
自訂一個button,要調整 button中的image(注意,不是backgroundImage) 和 title 文字的位置,只需要重寫 Button類獨對應的兩個方法即可:
首先,我們來建立一個 SuperButton繼承自 UIButton
//// SuperButton.h// SuperButton//// Created by 楊斌 on 14/12/25.// Copyright (c) 2014年 楊斌. All rights reserved.//#import <UIKit/UIKit.h>@interface SuperButton : UIButton@end
實現檔案
//// SuperButton.m// SuperButton//// Created by 楊斌 on 14/12/25.// Copyright (c) 2014年 楊斌. All rights reserved.//#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:@"[email protected]"] forState:UIControlStateNormal]; [self setImage:[UIImage imageNamed:@"[email protected]"] 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.代碼是經過刪減的,大家關鍵是重寫上面的兩個方法,重新繪製矩形,即可
ios代碼調整button圖片image文字title位置