iOS知识点~m

iOS——自定义button的几种方法

2017-06-26  本文已影响627人  艳晓

自定义button主要分为两大类。
1、在UIButton的基础上,进行继承,更改button中imageView和label的位置和大小。

图文相对位置变化

2、使用UIView实现button构成和功能。这种方法非常自由,button控件我们可以选择任意自己想用的多个控件,效果也会更加丰富。但是实现比上一种要复杂一些。

屏幕录制.gif

一、继承UIButton

自定义button方法一:可以通过子类化按钮来定制属于你自己的按钮类——自定义一个类继承自,然后用这个子类创建按钮即可;

1.1

在子类化的时候你可以重载下面这些方法,这些方法返回CGRect结构,指明了按钮每一组成部分的边界。
注意:不要直接调用这些方法, 这些方法是你写给系统调用的

下面是系统提供的方法

 // 返回背景边界(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

@end
#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);
}
@end

通过上面两个方法改变图片和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];
自定义button

通过上面两个方法改变图片和label的位置,我们可以对图片和label的位置按要求进行设置了

上一篇下一篇

猜你喜欢

热点阅读