自定义按钮的 imageView 和 titleLabel 的位置

#pragma mark - 设置按钮内的 imageView titleLabelframe (就是重写按钮的titleRectForContentRect: titleRectForContentRect:)这个类是继承自 UIButton所以可以重写这两个方法

// - 方案1.重写按钮的titleRectForContentRect: titleRectForContentRect:方法

/**

 *  设置按钮内部的 imageViewframe

 *

 *  @param contentRect按钮的尺寸

 *

 *  @return内部的 imageView frame

 */

-(CGRect)titleRectForContentRect:(CGRect)contentRect{

     CGFloat x = 80;

     CGFloat y = 0;

     CGFloat height = contentRect.size.height;

     CGFloat width = 13;

    return  CGRectMake(x, y, width, height);

}



/**

 *  设置按钮内部的 titleLabelframe

 *

 *  @param contentRect按钮的尺寸

 *

 *  @return内部的 titleLabel frame

 */

- (CGRect)imageRectForContentRect:(CGRect)contentRect{

    CGFloat x = 0;

    CGFloat y = 0;

    CGFloat height = contentRect.size.height;

    CGFloat width = 80;

    return  CGRectMake(x, y, width, height);

}



// 目的:想在系统计算和设置完按钮的尺寸后,再修改一下尺寸
/**
 *  重写setFrame:方法的目的:拦截设置按钮尺寸的过程
 *  如果想在系统设置完控件的尺寸后,再做修改,而且要保证修改成功,一般都是在setFrame:中设置
 */
- (void)setFrame:(CGRect)frame
{
    frame.size.width += HWMargin;
    [super setFrame:frame];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    // 如果仅仅是调整按钮内部titleLabel和imageView的位置,那么在layoutSubviews中单独设置位置即可
    
    // 1.计算titleLabel的frame
    self.titleLabel.x = self.imageView.x;
    
    // 2.计算imageView的frame
    self.imageView.x = CGRectGetMaxX(self.titleLabel.frame) + HWMargin;
}

- (void)setTitle:(NSString *)title forState:(UIControlState)state
{
    [super setTitle:title forState:state];

    // 只要修改了文字,就让按钮重新计算自己的尺寸
    [self sizeToFit];
}

- (void)setImage:(UIImage *)image forState:(UIControlState)state
{
    [super setImage:image forState:state];
    
    // 只要修改了图片,就让按钮重新计算自己的尺寸
    [self sizeToFit];
}




// 按钮高亮的时候。不要去调整图片(不要调整图片会灰色)

    self.adjustsImageWhenHighlighted =NO;

//    self.adjustsImageWhenDisabled




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值