iOS button 文字图片上下/左右排布
2017-04-12 本文已影响0人
剁椒鱼尾
网上之前的方法:
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)];
左右:(因为默认button 图片在左,文字在右, 下面代码是反过来的: 文字 图片)
[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)];
我不确定是不是因为他们的btn.titleLabel的文字宽度一样,所以没发生问题
当我用的时候,图片左右偏移量是错乱的,像这样:
所以,setImageEdgeInsets这一步操作前,需要计算titleLabel的实际宽度:
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];
//关键步骤
shareBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
//调用方法
[self initButton:shareBtn];
}
//方法直接调用
-(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)];
}
结果:
false2.png