自定义UIButton的封装

1.创建一个类名(EncapsulationButton)继承自UIButton

2.在EncapsulationButton的.h文件中创建类方法 自定义要接收的参数

+(EncapsulationButton *)buttonWithType:(UIButtonType)type Frame:(CGRect)frame ButtonTitle:(NSString *)buttonTitle ButtonBackGroundColor:(UIColor *)buttonBackGroundColor ButtonBackgroundImage:(NSString *)buttonBackImage;

3.在EncapsulationButton.m文件中实现此方法

+(EncapsulationButton *)buttonWithType:(UIButtonType)type Frame:(CGRect)frame ButtonTitle:(NSString *)buttonTitle ButtonBackGroundColor:(UIColor *)buttonBackGroundColor ButtonBackgroundImage:(NSString *)buttonBackImage
{
    //创建按钮对象
    EncapsulationButton *button = [EncapsulationButton buttonWithType:type];
    
    //设置按钮尺寸
    button.frame = frame;
    
    //设置按钮标题
    [button setTitle:buttonTitle forState:UIControlStateNormal];
    
    //设置按钮背景色
    button.backgroundColor = buttonBackGroundColor;
    
    //设置按钮背景图
    [button setBackgroundImage:[UIImage imageNamed:buttonBackImage] forState:UIControlStateNormal];
    
    //设置按钮文字居中
    button.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    //返回一个按钮
    return button;
}

4.在需要创建自定义按钮的类中引用头文件

    //创建一个自定义按钮
    EncapsulationButton *btn = [EncapsulationButton buttonWithType:UIButtonTypeCustom Frame:CGRectMake(50, 100, 100, 38) ButtonTitle:@"按钮" ButtonBackGroundColor:[UIColor redColor] ButtonBackgroundImage:@"1"];
    
    //将控件添加到视图上
    [self.view addSubview:btn];

你可能感兴趣的:(自定义UIButton的封装)