UIButton之自定义button

来源:互联网 发布:pid算法实例讲解 编辑:程序博客网 时间:2024/05/21 19:39

如果想实现“图1”风格的按钮,图片和title一直保持在button的左边,我们可以通过设置contentEdgeInsets属性、titleEdgeInsets属性来实现。但是,这种方法的缺点就是当button的frame属性发生变化时,就达不到效果了!

这时候就要封装一个自定义button类,继承自UIButton类,然后重写UIButton类中的-imageRectForContentRect: 和 –titleRectForContentRect:方法来实现我们的需求。
这里写图片描述图1


自定义类的实现部分

#import "SDDButton.h"#define EDGELEFT 10#define IMAGEWIDTH 15#define IMAGEHEIGHT 15@implementation SDDButton-(CGRect)titleRectForContentRect:(CGRect)contentRect{    return CGRectMake(IMAGEWIDTH+EDGELEFT*2, 0, contentRect.size.width-IMAGEWIDTH-EDGELEFT*2, contentRect.size.height);}-(CGRect)imageRectForContentRect:(CGRect)contentRect{    return CGRectMake(EDGELEFT, (contentRect.size.height-IMAGEHEIGHT)/2, IMAGEWIDTH, IMAGEHEIGHT);}@end

调用自定义类:先导入自定义类名 #import “SDDButton.h”

    SDDButton *btn = [[SDDButton alloc]initWithFrame:CGRectMake(20, 200, 100, 40)];       [btn setBackgroundColor:[UIColor greenColor]];    [btn setEnabled:YES];    [btn setImage:[UIImage imageNamed:@"addSDjia"] forState:UIControlStateNormal];    [btn setAdjustsImageWhenHighlighted:YES];    [btn setTitle:@"添加" forState:UIControlStateNormal];    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];    [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:15]];    [self.view addSubview:btn];                 //运行效果:见图2    //修改Frame属性为CGRectMake(20, 200, 100, 40) //运行效果:见图3

这里写图片描述图2
这里写图片描述图3

0 0
原创粉丝点击