现在App的底部栏、侧边栏、顶部栏经常出现一些包含图像和文字的Item,以前用按钮上面添加label和imageView, 想想实在是对资源的浪费。。
图1 — 底部栏 图2 — 侧边栏
apple已经考虑到这点,UIButton里其实已经自带了label和imageView,虽然不能像设置frame一样设置它们的位置,
但是可以通过设置四个边的EdgeInset来“挤”。
但是"挤"是个技术活,要使得图片和文字怪怪的听话可不是简单,一点点的调整很繁琐,参考了stackoverflow上的回答后,可以基本解决了。
文字和图片的摆放一般有两种情况: 上下摆放和左右摆放;
情况一:
1 // the space between the image and text 2 CGFloat spacing = 6.0; 3 4 // lower the text and push it left so it appears centered 5 // below the image 6 CGSize imageSize = button.imageView.frame.size; 7 button.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (imageSize.height + spacing), 0.0); 8 9 // raise the image and push it right so it appears centered 10 // above the text 11 CGSize titleSize = button.titleLabel.frame.size; 12 button.imageEdgeInsets = UIEdgeInsetsMake(- (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
The following version contains changes to support iOS 7+ that have been recommended in comments below. I haven‘t tested this code myself, so I‘m not sure how well it works or whether it would break if used under previous versions of iOS.
根据底下的评论建议,下面的代码包含更改后支持iOS7以上版本。我自己还没有测试这代码,不知道是否能用,或者在iOS7以前的版本中会崩溃。
1 // the space between the image and text 2 CGFloat spacing = 6.0; 3 4 // lower the text and push it left so it appears centered 5 // below the image 6 CGSize imageSize = button.imageView.image.size; 7 button.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (imageSize.height + spacing), 0.0); 8 9 // raise the image and push it right so it appears centered 10 // above the text 11 CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: button.titleLabel.font}]; 12 button.imageEdgeInsets = UIEdgeInsetsMake(- (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
情况二:
1 CGFloat spacing = 10; // the amount of spacing to appear between image and title 2 tabBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing); 3 tabBtn.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);
原文: http://www.cnblogs.com/A--G/p/5131401.html
参考链接: 1. http://stackoverflow.com/questions/2451223/uibutton-how-to-center-an-image-and-a-text-using-imageedgeinsets-and-titleedgei
UIButton 使用imageEdgeInsets和titleEdgeInsets属性
原文:http://www.cnblogs.com/A--G/p/5131401.html