自定義button上的title和image的位置

第一種方法

首先獲取button上的titleLabel和imageView的寬和高,

imageView的寬高:

CGFloat imageWith = self.imageView.frame.size.width;

CGFloat imageHeight = self.imageView.frame.size.height;

當(dāng)然也可以通過(guò)這種方法獲取imageView的大小

CGFloat imageWidth = CGImageGetWidth([UIImage imageNamed:@"driving"].CGImage);

CGFloat imageHeight = CGImageGetHeight([UIImage imageNamed:@"driving"].CGImage);

不過(guò)需要注意的是需要辨別獲取的圖片是一倍圖,還是二倍圖亦或者三倍圖,然后用imageWidth和imageHeigt除以倍數(shù)

titleLabel的寬高:

CGFloat labelWidth = 0.0;

CGFloat labelHeight = 0.0;

if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {

// 由于iOS8中titleLabel的size為0,用下面的這種設(shè)置

labelWidth = self.titleLabel.intrinsicContentSize.width;

labelHeight = self.titleLabel.intrinsicContentSize.height;

} else {

labelWidth = self.titleLabel.frame.size.width;

labelHeight = self.titleLabel.frame.size.height;

}

然后設(shè)置button的imageEdgeInsets和labelEdgeInsets屬性

1.image在上,label在下

imageEdgeInsets = UIEdgeInsetsMake(-labelHeight-space/2.0, 0, 0, -labelWidth);

labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith, -imageHeight-space/2.0, 0);

2.image在左,label在右

imageEdgeInsets = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0);

labelEdgeInsets = UIEdgeInsetsMake(0, space/2.0, 0, -space/2.0);

3.image在下,label在上

imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth);

labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space/2.0, -imageWith, 0, 0);

4.image在右,label在左

imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+space/2.0, 0, -labelWidth-space/2.0);

labelEdgeInsets = UIEdgeInsetsMake(0, -imageWith-space/2.0, 0, imageWith+space/2.0);

第二種

通過(guò)自定義button,重寫(xiě)button的以下兩個(gè)方法

-(CGRect)titleRectForContentRect:(CGRect)contentRect;

-(CGRect)imageRectForContentRect:(CGRect)contentRect;

這里面你可以隨意設(shè)置titleLabel和imageView的位置

第三種

創(chuàng)建Button的時(shí)候使用UIButton *selectedButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 100, 100, 30)];來(lái)創(chuàng)建,然后把你需要添加的titleLabel或者imageView作為子視圖添加到button上,但是蘋果官方更推薦使用buttonWithType,因?yàn)檫@個(gè)是唯一一個(gè)設(shè)置buttonType的地方,并且這個(gè)方法正在MRC中可以自動(dòng)釋放button,而initWithFrame需要手動(dòng)釋放.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容