先看图,众所周知,一个button上面有一个imageview和一个titleLabel,有时候我们需要根据需求及美观来改变他们的排布,以上就是两种最常见的排布
做法如下:
首先创建一个继承自UIButton的类,并且做基本的初始化设置
#import <UIKit/UIKit.h>
@interface CustomButton : UIButton
@end
- (instancetype)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if(self){
// 高亮的时候不要自动调整图标
self.adjustsImageWhenHighlighted =NO;
// self.titleLabel.font = [UIFont boldSystemFontOfSize:17];
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
[selfsetImage:[UIImageimageNamed:@"378-close"]forState:UIControlStateNormal];
[selfsetTitle:@"300"forState:UIControlStateNormal];
self.titleLabel.textAlignment =NSTextAlignmentCenter;
self.layer.cornerRadius =2;
}
return self;
}
下面重点来了!通过button自带的内部控件的布局方法来达到我们想要的效果即可
//对button内部的imageView进行布局,注意宽度这里是100
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imgY = 50;
CGFloat imgW = 100;
CGFloat imgX =0;
CGFloat imgH = 50;
return CGRectMake(imgX, imgY, imgW, imgH);
}
//对button内部的titleLabel进行布局
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleY = 0;
CGFloat titleX = 0;
CGFloat titleW = 100;
CGFloat titleH = 50;
return CGRectMake(titleX, titleY, titleW, titleH);
}
(效果图1)
至此,我们就弄出button的标题在上方,imageView在下方的效果!
同理,只要稍作修改,就可以改成左右排布
//对button内部的imageView进行布局,注意宽度这里是50
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imgY = 0;
CGFloat imgW = 50;
CGFloat imgX = 50;
CGFloat imgH = 100;
return CGRectMake(imgX, imgY, imgW, imgH);
}
//对button内部的titleLabel进行布局
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleY = 0;
CGFloat titleX = 0;
CGFloat titleW = 50;
CGFloat titleH = 100;
return CGRectMake(titleX, titleY, titleW, titleH);
}
(效果图2)