#pragma mark - 设置按钮内的 imageView和 titleLabel的frame (就是重写按钮的titleRectForContentRect:和 titleRectForContentRect:)这个类是继承自 UIButton的所以可以重写这两个方法
// - 方案1.重写按钮的titleRectForContentRect:和 titleRectForContentRect:方法
/**
* 设置按钮内部的 imageView的frame
*
* @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);
}
/**
* 设置按钮内部的 titleLabel的frame
*
* @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