有时候,我们想的需求是改变系统UIButton中image和label的位置,怎么办呢?
重写UIButton的布局即可!
自定义+浅析UIButton:
步骤:
1.先创建一个类(例如,取名为ZFButton),继承UIButton,然后类中先包含initWithFrame、initWithCoder、titleRectForContentRect、imageRectForContentRect这四个方法
- initWithFrame:纯代码布局的时候,frame设置必定会用这个方法,所以从写这个方法。可以在这个方法里面设置UIButton中image和lable的属性,例如:label的居中、image的content mode等等...。
- initWithCoder:使用storyboard布局时候,不会调用initWithFrame,而会调用initWithCoder。这个方法里面设置的东西和initWithFrame一样。
- titleRectForContentRect:手动调整UIButton中label的frame。参数是整个UIButon。
- imageRectForContentRect:手动调整UIButton中image的frame。参数是整个UIButton。
2.创建一个这个ZFButton的按钮,然后设置这个按钮的文本和图片。
3.把按钮加入self.view中。完成。
- titleRectForContentRect:这个方法和imageRectForContentRect在UIButton创建的时候会执行一次,并且在设置按钮文本的时候又会执行一次,所以程序中会多次执行这个方法。
- imageRectForContentRect:这个方法和titleRectForContentRect在UIButton创建的时候会执行一次,并且在设置按钮image时候又会执行一次,所以程序中会多次执行这个方法。
需求中,一般都是图上字下,或者图左字右这两种。
所以,我只演示这两种。其余的需求可以自己举一反三。
//会被多次调用,alloc,set都会调用
-(CGRect)titleRectForContentRect:(CGRect)contentRect
{
/*
图上字下
*/
// CGFloat titleX = 0;
// CGFloat titleY = contentRect.size.height * 0.75;
// CGFloat titleW = contentRect.size.width;
// CGFloat titleH = contentRect.size.height - titleY;
// return CGRectMake(titleX, titleY, titleW, titleH);
/*
图左字右
*/
CGFloat titleX = CGRectGetMaxX(self.imageView.frame);
CGFloat titleY = 0;
CGFloat titleW = CGRectGetWidth(contentRect) * 0.7 ;
CGFloat titleH = CGRectGetHeight(contentRect);
return CGRectMake(titleX, titleY, titleW, titleH);
}
//会被多次调用,alloc,set都会调用
-(CGRect)imageRectForContentRect:(CGRect)contentRect
{
/*
图上字下
*/
// CGFloat imageW = CGRectGetWidth(contentRect);
// CGFloat imageH = contentRect.size.height * 0.7;
// return CGRectMake(0, 0, imageW, imageH);
/*
图左字右
*/
CGFloat imageW = CGRectGetWidth(contentRect) * 0.3;
CGFloat imageH = CGRectGetHeight(contentRect);
return CGRectMake(0, 0, imageW, imageH);
}
参考代码:https://github.com/HZhenF/CustomButton.git