第一次遇到一個(gè)按鈕需要 圖片和文字上下居中容劳,先反復(fù)設(shè)置了titleEdgeInsets 和 imageEdgeInsets,直到肉眼看來(lái)居中了
下一次又遇到這個(gè)需求闸度,發(fā)現(xiàn)還要猜這兩個(gè)屬性 上下左右的間距
果斷受不了了鸭蛙,直接在按鈕里面add imageview 和 label,用這個(gè)方法來(lái)寫(xiě)筋岛,frame不是問(wèn)題了支救。
下一次再遇到這個(gè)問(wèn)題逢净,不過(guò)又多了個(gè)需求,需要有高亮和選擇的狀態(tài)顯示嘱么,我x 還得監(jiān)聽(tīng)父控件的狀態(tài)來(lái)改變子控件的顯示
這回寝凌,感覺(jué)要死磕了
找了下文檔和一些文章
對(duì) titleEdgeInsets 和 imageEdgeInsets柒傻,contentEdgeInsets 有了更清晰的了解
然后寫(xiě)了個(gè)unbutton的分類
廢話不多說(shuō),直接上代碼
-
(UIButton *)ButtonWithFont:(CGFloat )font image:(NSString *)image imageH:(NSString *)imageH imageSlected:(NSString *)imageSlected title:(NSString *)title imageCenterRatio:(CGFloat )imageRatio titleCenterRatio:(CGFloat )titleRatio {
UIButton *btn = [[UIButton alloc] init];
UIImage *btnImage = [UIImage imageNamed:image];
CGFloat imageWidth = CGImageGetWidth(btnImage.CGImage);
CGFloat imageHeight = CGImageGetHeight(btnImage.CGImage);if ([UIScreen mainScreen].scale == 3.0f) {
imageWidth *= 0.5f;
imageHeight *= 0.5f;
}NSString *btnText = title;
UIFont *btnFont = [UIFont systemFontOfSize:font];
NSDictionary *attrs = @{NSFontAttributeName : btnFont};
CGSize labelSize = [btnText boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine attributes:attrs context:nil].size;CGFloat labelHeight = labelSize.height;
CGFloat labelWidth = labelSize.width;CGFloat btnH = imageHeight + labelHeight;
CGFloat btnW = imageWidth + labelWidth;btn.bounds = CGRectMake(0, 0, btnW, btnH);
[btn setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:imageH] forState:UIControlStateHighlighted];
[btn setImage:[UIImage imageNamed:imageSlected] forState:UIControlStateSelected];
[btn setTitle:title forState:UIControlStateNormal];
[btn.titleLabel setFont:[UIFont systemFontOfSize:font]];
CGPoint imageEndCenter = CGPointMake(btnW / 2, btnH * imageRatio);
CGPoint imageStartCenter = btn.imageView.center;
CGFloat top1 = imageEndCenter.y - imageStartCenter.y;
CGFloat left1 = imageEndCenter.x - imageStartCenter.x;
CGFloat bottom1 = -top1;
CGFloat right1 = -left1;
btn.imageEdgeInsets = UIEdgeInsetsMake(top1, left1, bottom1, right1);
CGPoint titleEndCenter = CGPointMake(btnW / 2, btnH * titleRatio);
CGPoint titleStartCenter = btn.titleLabel.center;
CGFloat top2 = titleEndCenter.y - titleStartCenter.y;
CGFloat left2 = titleEndCenter.x - titleStartCenter.x;
CGFloat bottom2 = -top2;
CGFloat right2 = -left2;
btn.titleEdgeInsets = UIEdgeInsetsMake(top2, left2, bottom2, right2);
btn.contentEdgeInsets = UIEdgeInsetsMake(0, -labelWidth/2, 0, -labelWidth/2);
return btn;
}