最近在做一个小App,首页布局如下,每一个Cell都是一张图片下面跟一行描述文字:

SZTool screenshot

首先想到的是自定义一个View,用一个UIImageView和UILabel来组合实现。后面一想,UIButton内部不就是一个UIImageView和UILabel吗?能不能通过改变UIButton的样式来实现呢?经过一番探索,找到了解决完美解决的办法,主要是改变UIButton的titleEdgeInsetsimageEdgeInsets。代码也很简单:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 将文字放在图片之下
*/
- (void)textUnderImageButton:(UIButton *)button
{
// the space between the image and text
CGFloat spacing = 6.0;

// lower the text and push it left so it appears centered below the image
CGSize imageSize = button.imageView.image.size;
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);

// raise the image and push it right so it appears centered above the text
CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: button.titleLabel.font}];
button.imageEdgeInsets = UIEdgeInsetsMake(- (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
}

用UIbutton来实现还有一个好处是自带了点击效果,确实省事!