網(wǎng)上之前的方法:
http://www.cnblogs.com/LynnAIQ/p/5908664.html
上下:
//使圖片和文字水平居中顯示
self.rechargeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
//文字距離上邊框的距離增加imageView的高度恋沃,距離左邊框減少imageView的寬度,距離下邊框和右邊框距離不變
[self.rechargeButton setTitleEdgeInsets:UIEdgeInsetsMake(self.rechargeButton.imageView.frame.size.height+10 ,-self.rechargeButton.imageView.frame.size.width, 0.0,0.0)];
//圖片距離右邊框距離減少圖片的寬度,其它不邊
[self.rechargeButton setImageEdgeInsets:UIEdgeInsetsMake(-10, 0.0,0.0, -self.rechargeButton.titleLabel.bounds.size.width)];
左右:(因?yàn)槟J(rèn)button 圖片在左,文字在右, 下面代碼是反過(guò)來(lái)的: 文字 圖片)
[self.DetailButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -self.DetailButton.imageView.bounds.size.width, 0, self.DetailButton.imageView.bounds.size.width)];
[self.DetailButton setImageEdgeInsets:UIEdgeInsetsMake(0, self.DetailButton.titleLabel.bounds.size.width, 0, -self.DetailButton.titleLabel.bounds.size.width)];
我不確定是不是因?yàn)樗麄兊腷tn.titleLabel的文字寬度一樣,所以沒(méi)發(fā)生問(wèn)題
當(dāng)我用的時(shí)候蚀同,圖片左右偏移量是錯(cuò)亂的堪滨,像這樣:
false1.png
所以桑驱,setImageEdgeInsets這一步操作前将塑,需要計(jì)算titleLabel的實(shí)際寬度:
CGSize maxSize = CGSizeMake(1000, shareBtn.titleLabel.height);
CGSize fitSize = [shareBtn.titleLabel sizeThatFits:maxSize];
CGFloat w_titleLabel = fitSize.width;
完整代碼:
NSArray *array1 = @[@"微信",@"朋友圈",@"QQ",@"QQ空間"];
NSArray *array2 = @[@"fenxiangweixin",@"fenxiangpyq",@"fenxiangqq",@"fenxiangkongj"];
CGFloat wid_icon = (AL_DEVICE_WIDTH-20)/4;
for (int i=0; i<array1.count; i++) {
UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:shareBtn];
[shareBtn setImage:[UIImage imageNamed:array2[i]] forState:UIControlStateNormal];
shareBtn.frame = CGRectMake(10+i*wid_icon, iconA.bottom, wid_icon, wid_icon);
[shareBtn setTitle:array1[i] forState:UIControlStateNormal];
shareBtn.titleLabel.textAlignment = 1;
shareBtn.titleLabel.font = FontSystem(17);
[shareBtn setTitleColor:UICOLOR_HEX(0x000000) forState:UIControlStateNormal];
[shareBtn addTarget:self action:@selector(inviteMyFriend:) forControlEvents:UIControlEventTouchUpInside];
[shareBtn setAdjustsImageWhenDisabled:NO];
//關(guān)鍵步驟
shareBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
//調(diào)用方法
[self initButton:shareBtn];
}
//方法直接調(diào)用
-(void)initButton:(UIButton*)shareBtn{
CGSize maxSize = CGSizeMake(1000, shareBtn.titleLabel.height);
CGSize fitSize = [shareBtn.titleLabel sizeThatFits:maxSize];
CGFloat w_titleLabel = fitSize.width;
CGFloat w_imageV = shareBtn.imageView.width;
CGFloat h_imageV = shareBtn.imageView.height;
//文字距離上邊框的距離增加imageView的高度,距離左邊框減少imageView的寬度卜朗,距離下邊框和右邊框距離不變
[shareBtn setTitleEdgeInsets:UIEdgeInsetsMake(h_imageV+20 ,-w_imageV, 0.0,0.0)];
//圖片距離右邊框距離減少圖片的寬度拔第,其它不變
[shareBtn setImageEdgeInsets:UIEdgeInsetsMake(-10, 0.0,0.0, -w_titleLabel)];
}
結(jié)果:
false2.png