// 返回背景边界(background)
- (CGRect)backgroundRectForBounds:(CGRect)bounds;
// 返回内容边界 标题+图片+标题与图片之间的间隔(title + image + the image and title separately)
- (CGRect)contentRectForBounds:(CGRect)bounds;
// 返回标题边界
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
// 返回图片边界
- (CGRect)imageRectForContentRect:(CGRect)contentRect;
-(CGRect)backgroundRectForBounds:(CGRect)bounds 该函数返回的是背景view的大小,参数bounds是button的大小,即button.frame
如果:return bounds
此时背景view和button的大小相同,是默认的大小
如果:return CGRectMake(0, 0, 50, 50),且button.frame = CGRectMake(0, 0, 100, 100)
此时背景view的大小是{{0,0},{50,50}},而button的大小是{{0,0},{100,100}},在背景view之外的button是透明的且不能改变颜色,它可以响应点击事件
如果:return CGRectMake(0, 0, 100, 100),且button.frame = CGRectMake(0, 0, 50, 50)
此时分两种情况,一种是layer.masksToBounds = YES,button的背景view和frame都是{{0,0},{50,50}};另一种layer.masksToBounds = NO,button的背景view的大小是{{0,0},{100,100}},button.frame大小是{{0,0},{50,50}},此时界面显示是一个{{0,0},{100,100}}的button,但是只有button的{{0,0},{50,50}}范围内才会响应点击事件
-(CGRect)contentRectForBounds:(CGRect)bounds 该函数返回内容view的大小,内容view包括title view 、image view 和二者之间的间隔,参数bounds是button的大小,即button.frame
如果:return bounds
此时在返回title view边界和image view边界函数中的contentRect参数的值为button.bounds
如果:return CGRectMake(0, 0, 100, 100)
此时在返回title view边界和image view边界函数中的contentRect参数的值为{{0,0},{100,100}}
-(CGRect)titleRectForContentRect:(CGRect)contentRect 该函数返回标题view的大小,参数contentRect由函数-(CGRect)contentRectForBounds:(CGRect)bounds确定
-(CGRect)imageRectForContentRect:(CGRect)contentRect 该函数返回图片view的大小,参数contentRect由函数-(CGRect)contentRectForBounds:(CGRect)bounds确定
一个最简单的代码示例:
#import <UIKit/UIKit.h>
@interface MyButton4 : UIButton
#import "MyButton4.h"
@implementation MyButton4
// title的位置
- (CGRect)titleRectForContentRect:(CGRect)contentRect{
return CGRectMake(0, 100, self.bounds.size.width, 50);
//背景图的位置
- (CGRect)backgroundRectForBounds:(CGRect)bounds{
return CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
通过上面两个方法改变图片和label的位置,我们可以对图片和label的位置按要求进行设置了
MyButton4 *button4 = [[MyButton4 alloc] initWithFrame:CGRectMake(10, 220, 200, 160)];
button4.backgroundColor = [UIColor orangeColor];
[button4 setTitle:@"猫咪Button" forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
[button4 setBackgroundImage:[UIImage imageNamed:@"test.jpg"] forState:UIControlStateNormal];
[button4 addTarget:self action:@selector(button4Clicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button4];