自定义Button+浅析Button调用过程

有时候,我们想的需求是改变系统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

点击打开链接


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值