按钮UIButton内图片和文字位置的设置(两种方式)

  首先创建一个类,注意需要继承自UIButton,并在这个类中重写layoutSubview方法代码如下(图片在上,文字在下):

  注:x,y,width,height已经进行封装过的,封装方法详见     http://www.cnblogs.com/hissia/p/5636534.html

 1 - (void)layoutSubviews
 2 {
 3     [super layoutSubviews];
 4     //设置图片的尺寸
 5     self.imageView.x = 0;
 6     self.imageView.y = 0;
 7     self.imageView.width = self.width;
 8     self.imageView.height = self.imageView.width;
 9     //设置label的尺寸
10     self.titleLabel.x = 0;
11     self.titleLabel.y = self.imageView.height;
12     self.titleLabel.width = self.width;
13     self.titleLabel.height = self.height - self.imageView.height;
14 }

对labe的文字进行处理:

1 - (void)awakeFromNib
2 {
3     [self setup];
4 }
5 - (void)setup
6 {
7     self.titleLabel.textAlignment = NSTextAlignmentCenter;
8 }

如果想以后用这个类创建的Button都具有图片在上,文字在下面的按钮,可以添加initWithFrame方法,如下:

1 - (instancetype)initWithFrame:(CGRect)frame
2 {
3     if (self = [super initWithFrame:frame]) {
4         [self setup];
5     }
6     return self;
7 }

 当然了,可以在storyboard或Xib中直接设置。

点击button按钮后显示如图显示:

可以选择image或者label或者content三种,然后下面inset中选择尺寸

原文地址:https://www.cnblogs.com/hissia/p/5621691.html