美文网首页iOS 基本开发iOS学习UI 界面
iOS 调整UIButton 图片(imageView)与文字(

iOS 调整UIButton 图片(imageView)与文字(

作者: emily_sky | 来源:发表于2016-08-19 14:35 被阅读7769次

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); 图片在左文字在右,而且整体水平和垂直居中 。比如下面这个图文按钮:

Paste_Image.png

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

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

设置图片在右文字在左:

Paste_Image.png
// 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);

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


Paste_Image.png
// 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);

设置图片左对齐:

Paste_Image.png
//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);

设置文字右对齐:


Paste_Image.png
//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);

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

Paste_Image.png
_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));

相关文章

网友评论

  • wahkim:有个问题 设置图片和文字偏移的时候self.locationBtn.imageView.bounds.size.width和self.locationBtn.titleLabel.bounds.size.width值都为0
    万劫不败:使用self.locationBtn.currentImage.size.width
  • 简简728:图片大小怎么修改呀
  • 梵尘_341b:为什么调整btn布局后 ,titleLabel部分不能响应事件?
    没有故事的宋同学:@吃不胖可咋整啊 titileLabel 是否超出btn的frame?超出肯定是不能响应事件的
    HappyJiuOk:同问

本文标题:iOS 调整UIButton 图片(imageView)与文字(

本文链接:https://www.haomeiwen.com/subject/fbdbsttx.html