iOS开发 关于button的titleLabel和imageView的位置

原理

1.titleEdgeInsets是title相对于其上下左右的inset,跟tableView的contentInset是类似的;
2.如果只有title,那它上下左右都是相对于button的,image也是一样;
3.如果同时有image和label,那这时候image的上左下是相对于button,右边是相对于label的;title的上右下是相对于button,左边是相对于image的。
直接上代码,通常的设置我们会这样做:

[self.navView.centerButton setTitleEdgeInsets:UIEdgeInsetsMake(0.0, -CGRectGetWidth(self.navView.centerButton.imageView.frame), 0.0, CGRectGetWidth(self.navView.centerButton.imageView.frame) + self.arrowPadding)];
[self.navView.centerButton setImageEdgeInsets:UIEdgeInsetsMake(0.0, CGRectGetWidth(self.navView.centerButton.titleLabel.frame) + self.arrowPadding, 0.0, -CGRectGetWidth(self.navView.centerButton.titleLabel.frame))];

相对比较繁琐且每个地方都得设置。

下面我们通过category自定义button的titleLabel和imageView的位置,方便使用

typedef NS_ENUM(NSUInteger, MKButtonEdgeInsetsStyle) {
    MKButtonEdgeInsetsStyleTop, // image在上,label在下
    MKButtonEdgeInsetsStyleLeft, // image在左,label在右
    MKButtonEdgeInsetsStyleBottom, // image在下,label在上
    MKButtonEdgeInsetsStyleRight // image在右,label在左
};

@interface UIButton (ImageTitleSpacing)

/**
 *  设置button的titleLabel和imageView的布局样式,及间距
 *
 *  @param style titleLabel和imageView的布局样式
 *  @param space titleLabel和imageView的间距
 */
- (void)layoutButtonWithEdgeInsetsStyle:(MKButtonEdgeInsetsStyle)style
                        imageTitleSpace:(CGFloat)space;

运用分类一行代码即可实现。

这里参考GitHub上开源项目# MKButtonStyle
感谢作者# mokong分享

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容