在實(shí)際開發(fā)中闯割,系統(tǒng)默認(rèn)的UIButton不能滿足需求骇笔,需要對(duì)button進(jìn)行自定義省店。
UIButton的默認(rèn)布局是: title在右, image在左。
如果要實(shí)現(xiàn)title在左笨触,image在右懦傍,或者title、image在上/下芦劣,或者其他位置粗俱,就需要自定義button.
通常我們調(diào)整位置image和title的位置有兩種方式:
1、直接調(diào)整EdgeInsets
@property (nonatomic) UIEdgeInsets titleEdgeInsets;
@property (nonatomic) UIEdgeInsets imageEdgeInsets;
EdgeInsets是結(jié)構(gòu)體虚吟,上左下右去添加約束寸认,這里不重點(diǎn)講。
2串慰、自定義Button繼承自UIButton, 重寫如下方法:
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;
這里看看image偏塞、title在水平方向效果,豎直方向的可以自己試試邦鲫,下面有對(duì)應(yīng)的枚舉標(biāo)識(shí)灸叼。
代碼如下:
typedef NS_ENUM(NSInteger, KBMainButtonStyle) {
ImageLeftTitleRight = 0, //圖片左title右
ImageRightTitleLeft, //圖片右title左
ImageTopTitleDown, //圖片上title下
ImageDownTitleTop //圖片下title上
};
- (void)setButonStyle:(KBMainButtonStyle)buttonStyle imgFrame:(CGRect)imgFrame {
_buttonStyle = buttonStyle;
_imgFrame = imgFrame;
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
CGFloat originX = 0;
CGFloat originY = 0;
CGFloat width = 0;
CGFloat height = 0;
CGRect rec = CGRectZero;
switch (_buttonStyle) {
case ImageLeftTitleRight:
{
originX = _imgFrame.origin.x + _imgFrame.size.width;
originY = 0;
width = contentRect.size.width - originX;
height = contentRect.size.height;
rec = CGRectMake(originX, originY, width, height);
}
break;
case ImageRightTitleLeft:
{
originX = 0;
originY = 0;
width = contentRect.size.width - _imgFrame.size.width;
height = contentRect.size.height;
rec = CGRectMake(originX, originY, width, height);
}
break;
case ImageTopTitleDown:
{
originX = 0;
originY = _imgFrame.origin.y + _imgFrame.size.height;
width = contentRect.size.width;
height = contentRect.size.height - originY;
rec = CGRectMake(originX, originY, width, height);
}
break;
case ImageDownTitleTop:
{
originX = 0;
originY = 0;
width = contentRect.size.width;
height = contentRect.size.height - _imgFrame.size.height;
rec = CGRectMake(originX, originY, width, height);
}
break;
default:
break;
}
return rec;
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect {
return _imgFrame;
}
詳細(xì)代碼,見Demo