iOS UIButton文字与图片交换位置

释放双眼,带上耳机,听听看~!
  • UIButton默认,图片居左,文字在右,垂直居中显示,文字与图片没有间距,如下图:

可以通过设置UIButton中的titleEdgeInsets和imageEdgeInsets改变按钮的imageView与titleLabel的位置与间距,推荐给UIButton添加一个分类,将一下方法公开出来,方便所有的按钮调用

github Demo下载地址:https://github.com/yanhaiqiang/HQIconButton

1.图片居左,文字在右,垂直居中显示,文字与图片没有间距为10,如下图:

代码如下:

- (void)setIconInLeftWithSpacing:(CGFloat)Spacing
{
self.titleEdgeInsets = (UIEdgeInsets){
.top    = 0,
.left   = Spacing/2,
.bottom = 0,
.right  = -Spacing/2,
};
self.imageEdgeInsets = (UIEdgeInsets){
.top    = 0,
.left   = -Spacing/2,
.bottom = 0,
.right  = Spacing/2,
};
}

2.图片居右,文字在左,垂直居中显示,文字与图片没有间距为10,如下图:

代码如下:

- (void)setIconInRightWithSpacing:(CGFloat)Spacing
{
CGFloat img_W = self.imageView.frame.size.width;
CGFloat tit_W = self.titleLabel.frame.size.width;
self.titleEdgeInsets = (UIEdgeInsets){
.top    = 0,
.left   = - (img_W + Spacing / 2),
.bottom = 0,
.right  =   (img_W + Spacing / 2),
};
self.imageEdgeInsets = (UIEdgeInsets){
.top    = 0,
.left   =   (tit_W + Spacing / 2),
.bottom = 0,
.right  = - (tit_W + Spacing / 2),
};
}

3.图片居上,文字在下,垂直居中显示,文字与图片没有间距为10,如下图:

代码如下:

- (void)setIconInTopWithSpacing:(CGFloat)Spacing
{
CGFloat img_W = self.imageView.frame.size.width;
CGFloat img_H = self.imageView.frame.size.height;
CGFloat tit_W = self.titleLabel.frame.size.width;
CGFloat tit_H = self.titleLabel.frame.size.height;
self.titleEdgeInsets = (UIEdgeInsets){
.top    =   (tit_H / 2 + Spacing / 2),
.left   = - (img_W / 2),
.bottom = - (tit_H / 2 + Spacing / 2),
.right  =   (img_W / 2),
};
self.imageEdgeInsets = (UIEdgeInsets){
.top    = - (img_H / 2 + Spacing / 2),
.left   =   (tit_W / 2),
.bottom =   (img_H / 2 + Spacing / 2),
.right  = - (tit_W / 2),
};
}

4.图片居下,文字在上,垂直居中显示,文字与图片没有间距为10,如下图:

代码如下:

- (void)setIconInBottomWithSpacing:(CGFloat)Spacing
{
CGFloat img_W = self.imageView.frame.size.width;
CGFloat img_H = self.imageView.frame.size.height;
CGFloat tit_W = self.titleLabel.frame.size.width;
CGFloat tit_H = self.titleLabel.frame.size.height;
self.titleEdgeInsets = (UIEdgeInsets){
.top    = - (tit_H / 2 + Spacing / 2),
.left   = - (img_W / 2),
.bottom =   (tit_H / 2 + Spacing / 2),
.right  =   (img_W / 2),
};
self.imageEdgeInsets = (UIEdgeInsets){
.top    =   (img_H / 2 + Spacing / 2),
.left   =   (tit_W / 2),
.bottom = - (img_H / 2 + Spacing / 2),
.right  = - (tit_W / 2),
};
}

人已赞赏
iOS文章

Xcode快捷键

2020-3-29 15:18:01

iOS文章

iOS 自定义搜索框实时监听输入的内容变化

2020-3-29 16:33:03

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索