iOS 自定义button

自定义button的作用

有时候写项目会需要有label和imageView等等很多控件加在一起使用,我之前用很多个UI控件拼接使用,但是总感觉有点low,不够专业,就开始学习自定义button
再啰嗦一句:UIButton默认的布局是左侧image,右侧title,如果想要改变image与title的frame,直接设置是不会有效果的。可以通过titleEdgeInsets、imageEdgeInsets分别修改image与title的位置。也可以通过自定义button

效果图

此处我只放了一个button,若在cell或是多个button相同的情况下使用会很方便
在这里插入图片描述

代码实现

首先自定义button

@implementation TAYButton

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.titleLabel.font = [UIFont systemFontOfSize:15];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    return self;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect {
    CGFloat imageX = 0;
    CGFloat imageY = 0;
    CGFloat imageW = 30;
    CGFloat imageH = 30;
    return CGRectMake(imageX, imageY, imageW, imageH);
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect {
    CGFloat titleX = 30;
    CGFloat titleY = 0;
    CGFloat titleW = 50;
    CGFloat titleH = 30;
    return CGRectMake(titleX, titleY, titleW, titleH);
}

然后在项目中使用:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    TAYButton *tayButton = [[TAYButton alloc] initWithFrame:CGRectMake(50, 50, 100, 150)];
    [tayButton setTitle:@"pick" forState:UIControlStateNormal];
    [tayButton setImage:[UIImage imageNamed:@"pick.png"] forState:UIControlStateNormal];
    [self.view addSubview:tayButton];
    
}

使用函数

苹果给我们提供了4个API

- (CGRect)backgroundRectForBounds:(CGRect)bounds;
- (CGRect)contentRectForBounds:(CGRect)bounds;
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;

重写button的title

- (CGRect)titleRectForContentRect:(CGRect)contentRect;

重写button的image

- (CGRect)imageRectForContentRect:(CGRect)contentRect;

这里的contentRect就是你当前在使用自定义Button的控件的width和height。重写这个方法,可以让button的控件变换位置和改变大小。

其他两个我不经常用到,也就不班门弄斧了,见谅。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值