iOS关于自定义button的四个方法

自定义button会用到的四个方法

 // 返回背景边界(background)
- (CGRect)backgroundRectForBounds:(CGRect)bounds;  
// 返回内容边界 标题+图片+标题与图片之间的间隔(title + image + the image and title separately)
- (CGRect)contentRectForBounds:(CGRect)bounds;  
  // 返回标题边界
- (CGRect)titleRectForContentRect:(CGRect)contentRect;  
 // 返回图片边界
- (CGRect)imageRectForContentRect:(CGRect)contentRect; 

调用它们的时机:
1.当button上什么也没有加时,只会调用- (CGRect)contentRectForBounds:(CGRect)bounds; 这一个方法。

2.当button只设置了title时,会调用- (CGRect)contentRectForBounds:(CGRect)bounds; 和- (CGRect)titleRectForContentRect:(CGRect)contentRect;

3.当设置了image时,会- (CGRect)contentRectForBounds:(CGRect)bounds; 和- (CGRect)imageRectForContentRect:(CGRect)contentRect;

4.单单设置了backgroundimage时,才会调用- (CGRect)backgroundRectForBounds:(CGRect)bounds;这个方法。而且不会调用imag和title那俩个方法

下面分别解释一下各个方法意思:
-(CGRect)backgroundRectForBounds:(CGRect)bounds
该函数返回的是背景view的大小,参数bounds是button的大小,即button.frame。
默认返回的是 定义button时frame大小
但是如果在这个方法下面return的大小超过了定义时的frame,那么超过的部分不会响应点击事件,如果layer.masksToBounds = YES(默认是NO);
这样看直观一点
iOS关于自定义button的四个方法_第1张图片
虚线框是button的实际frame,只有点击那里才会触发点击事件
那么button的显示的图片是frame的大小,且图片内容也是frame的那一块iOS关于自定义button的四个方法_第2张图片
上面是masksToBounds = NO时。
下面是YES:
iOS关于自定义button的四个方法_第3张图片
当方法返回的宽高小于设置的frame时,图片大小是方法返回大小,图片之外的button是透明的,可以触发点击事件。
iOS关于自定义button的四个方法_第4张图片

  • (CGRect)titleRectForContentRect:(CGRect)contentRect;
    // 返回图片边界
  • (CGRect)imageRectForContentRect:(CGRect)contentRect;
  • 这俩个方法比较简单
    当setImage和settitle时,会分别调用上吗的方法,第一个是设置图片的位置,第二个是设置文字的文字。
    以上是对这四个方法的介绍。

你可能感兴趣的:(iOS关于自定义button的四个方法)