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); 图片在左文字在右,而且整体水平和垂直居中 。比如下面这个图文按钮:
为了最美观一点,可以设置图标与文字间距 。如下图:
//button标题的偏移量,这个偏移量是相对于图片的
_rightBut.titleEdgeInsets = UIEdgeInsetsMake(0, 12, 0, 0);
设置图片在右文字在左:
// 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);
设置图片在上,文字在下:
// 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);
设置图片左对齐:
//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);
设置文字右对齐:
//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);
设置文字左对齐,图片右对齐:
_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