iOS开发之调整UIButton 图片(imageView)与文字(titleLabel)的位置

UIButton可以同时设置Title和Image,UIButton有两个属性:titleEdgeInsets(top,left,bottom,right)和imageEdgeInsets(top,left,bottom,right),通过设置这两个,就可以实现所有需要的Button的样式
UIButton 的 默认状态下imageEdgeInsets = UIEdgeInsetsMake(0,0,0,0);titleEdgeInsets = UIEdgeInsetsMake(0,0,0,0); 图片在左文字在右,而且整体水平和垂直居中 。比如下面这个图文按钮:

1421888-0522a0239078e4c9.png
image

为了最美观一点,可以设置图标与文字间距 。如下图:

1421888-2f83722caa9c7cbd.png
image
//button标题的偏移量,这个偏移量是相对于图片的
_rightBut.titleEdgeInsets = UIEdgeInsetsMake(0, 12, 0, 0);

设置图片在右文字在左:

1421888-74c29b7a2edb7ffe.png
image
// button标题的偏移量 
self.locationBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -self.locationBtn.imageView.bounds.size.width+2, 0, self.locationBtn.imageView.bounds.size.width);
 // button图片的偏移量
self.locationBtn.imageEdgeInsets = UIEdgeInsetsMake(0, self.locationBtn.titleLabel.bounds.size.width, 0, -self.locationBtn.titleLabel.bounds.size.width);

设置图片在上,文字在下:

1421888-6509d9ebacb7d181.png
image
// button标题的偏移量
self.eightButton.titleEdgeInsets = UIEdgeInsetsMake(self.eightButton.imageView.frame.size.height+5, -self.eightButton.imageView.bounds.size.width, 0,0);
// button图片的偏移量
self.eightButton.imageEdgeInsets = UIEdgeInsetsMake(0, self.eightButton.titleLabel.frame.size.width/2, self.eightButton.titleLabel.frame.size.height+5, -self.eightButton.titleLabel.frame.size.width/2);

设置图片左对齐:

1421888-06c6aa43cc598817.png
image
//button文字的偏移量
 _Choosebutton1.titleEdgeInsets = UIEdgeInsetsMake(0,  -(_Choosebutton1.imageView.frame.origin.x+_Choosebutton1.imageView.frame.size.width), 0, 0);
//button图片的偏移量
_Choosebutton1.imageEdgeInsets = UIEdgeInsetsMake(0, -(_Choosebutton1.imageView.frame.origin.x ), 0, _Choosebutton1.imageView.frame.origin.x);

设置文字右对齐:

1421888-58e0677e64d6abf2.png
image
//button文字的偏移量
 _Choosebutton1.titleEdgeInsets = UIEdgeInsetsMake(0,  0, 0, -(_Choosebutton1.frame.size.width - _Choosebutton1.titleLabel.frame.origin.x -_Choosebutton1.titleLabel.frame.size.width));
//button图片的偏移量
_Choosebutton1.imageEdgeInsets = UIEdgeInsetsMake(0, -(_Choosebutton1.imageView.frame.origin.x ), 0, _Choosebutton1.imageView.frame.origin.x);

设置文字左对齐,图片右对齐:

1421888-f8840d7eb57661bc.png
image
_Choosebutton1.titleEdgeInsets = UIEdgeInsetsMake(0,  -(_Choosebutton1.titleLabel.frame.origin.x+20), 0, 0);

_Choosebutton1.imageEdgeInsets = UIEdgeInsetsMake(0, (_Choosebutton1.frame.size.width - _Choosebutton1.imageView.frame.origin.x - _Choosebutton1.imageView.frame.size.width), 0, -(_Choosebutton1.frame.size.width - _Choosebutton1.imageView.frame.origin.x - _Choosebutton1.imageView.frame.size.width));

作者:emily_sky
链接:https://www.jianshu.com/p/d23a8234729c

猜你喜欢

转载自blog.csdn.net/weixin_34353714/article/details/86988302