參考:
調(diào)整UIButton中的imageView和titleLabel的相對位置
==
通過調(diào)整子控件的【邊緣內(nèi)邊距】edgeInset來實現(xiàn):imageEdgeInsets 、titleEdgeInsets
這種方式感覺不好調(diào),調(diào)起來貌似不太準(zhǔn)
==
還是建議自定義按鈕的方式,而且其他地方用起來也方便
h文件
#import <UIKit/UIKit.h>
@interface Btn : UIButton
@end
m文件
#import "Btn.h"
@implementation Btn
// 自定義按鈕的frame方法
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.titleLabel.textAlignment = NSTextAlignmentCenter;
// 字體不分狀態(tài)
self.titleLabel.font = [UIFont systemFontOfSize:14];
self.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
self.backgroundColor = [UIColor clearColor];
}
return self ;
}
- (void)layoutSubviews
{
[super layoutSubviews];
CGFloat buttonW = self.frame.size.width;
CGFloat buttonH = self.frame.size.height;
CGFloat imageW = 20;
self.titleLabel.frame = CGRectMake(0, 0,buttonW - imageW + 5, buttonH);
self.imageView.frame = CGRectMake(self.titleLabel.frame.size.width - 5, 5, imageW, imageW);
}
@end
使用
_btn = [[Btn alloc] initWithFrame:CGRectMake(0, 0, left_width, 28)];