創(chuàng)建一個(gè)子類Button繼承自UIButton
- (void)awakeFromNib{
[super awakeFromNib];
[self setButtonContentCenter:self];
//[self setButtonContentLeft]; 根據(jù)需要與上面的方法二選其一
//寫在這里的作用是 xib畫的button 選擇這個(gè)類 會(huì)自動(dòng)調(diào)整位置
//如果想影響代碼創(chuàng)建的button需要重寫對(duì)應(yīng)構(gòu)造函數(shù)
}
-(void)setHighlighted:(BOOL)highlighted{
//重寫父類方法 會(huì)導(dǎo)致點(diǎn)擊沒有高亮
}
- (void)setSelected:(BOOL)selected{
[super setSelected:selected];
[self setButtonContentCenter:self];
//[self setButtonContentLeft];
}
//設(shè)置圖片在中上 文字在中下
-(void)setButtonContentCenter:(UIButton *) btn
{
CGSize imgViewSize,titleSize,btnSize;
UIEdgeInsets imageViewEdge,titleEdge;
//設(shè)置按鈕內(nèi)邊距
imgViewSize = btn.imageView.bounds.size;
titleSize = btn.titleLabel.bounds.size;
btnSize = btn.bounds.size;
CGFloat heightSpace = btnSize.height / 2.0 - imgViewSize.height;
imageViewEdge = UIEdgeInsetsMake(heightSpace,0.0, btnSize.height - imgViewSize.height - heightSpace, - titleSize.width);
[btn setImageEdgeInsets:imageViewEdge];
titleEdge = UIEdgeInsetsMake(imgViewSize.height + heightSpace, - imgViewSize.width, 0.0, 0.0);
[btn setTitleEdgeInsets:titleEdge];
}
//設(shè)置文字在左圖片在右
-(void)setButtonContentLeft:(UIButton *) btn
{
CGSize imgViewSize,titleSize,btnSize;
//設(shè)置按鈕內(nèi)邊距
imgViewSize = btn.imageView.bounds.size;
titleSize = btn.titleLabel.bounds.size;
btnSize = btn.bounds.size;
[self setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgViewSize.width - 2, 0, imgViewSize.width + 2)];
[self setImageEdgeInsets:UIEdgeInsetsMake(0, titleSize.width + 2, 0, - titleSize.width - 2)];
}