UIButton可以同時(shí)設(shè)置Title和Image,UIButton有兩個(gè)屬性:titleEdgeInsets(top,left,bottom,right)和imageEdgeInsets(top,left,bottom,right)诉探,通過(guò)設(shè)置這兩個(gè)读第,就可以實(shí)現(xiàn)所有需要的Button的樣式
UIButton 的 默認(rèn)狀態(tài)下imageEdgeInsets = UIEdgeInsetsMake(0,0,0,0);titleEdgeInsets = UIEdgeInsetsMake(0,0,0,0); 圖片在左文字在右锌介,而且整體水平和垂直居中 。比如下面這個(gè)圖文按鈕:
為了最美觀一點(diǎn),可以設(shè)置圖標(biāo)與文字間距 救崔。如下圖:
//button標(biāo)題的偏移量扶供,這個(gè)偏移量是相對(duì)于圖片的
_rightBut.titleEdgeInsets = UIEdgeInsetsMake(0, 12, 0, 0);
設(shè)置圖片在右文字在左:
// button標(biāo)題的偏移量
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);
設(shè)置圖片在上筛圆,文字在下:
// button標(biāo)題的偏移量
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);
設(shè)置圖片左對(duì)齊:
//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);
設(shè)置文字右對(duì)齊:
//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);
設(shè)置文字左對(duì)齊,圖片右對(duì)齊:
_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));