美文网首页iOS开发iOS 开发
自定义UIButton的封装

自定义UIButton的封装

作者: Stormstout | 来源:发表于2016-06-08 01:39 被阅读424次

    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的封装

        本文链接:https://www.haomeiwen.com/subject/escjdttx.html