UIButton图片文字控件位置自定义(图片居右文字居左、图片居中文字居中、图片居左文字消失等)

时间:2023-03-09 04:32:12
UIButton图片文字控件位置自定义(图片居右文字居左、图片居中文字居中、图片居左文字消失等)

在开发中经常会碰到需要对按钮中的图片文字位置做调整的需求。
第一种方式是通过设置按钮中图片文字的偏移量。通过方法setTitleEdgeInsets和setImageEdgeInsets实现

代码如下:

/*!**方式一***/
- (void)updateBtnStyle_rightImage:(UIButton *)btn { CGFloat btnImageWidth = btn.imageView.bounds.size.width;
CGFloat btnLabelWidth = btn.titleLabel.bounds.size.width;
CGFloat margin = ; btnImageWidth += margin;
btnLabelWidth += margin; [btn setTitleEdgeInsets:UIEdgeInsetsMake(, -btnImageWidth, , btnImageWidth)];
[btn setImageEdgeInsets:UIEdgeInsetsMake(, btnLabelWidth, , -btnLabelWidth)];
}

这种方式对普通的需求是可以满足的,但是操作起来麻烦,不是那么直观。对于像修改图片子控件的宽高这种高度自定义的行为是很难实现的。

第二种方式则可以像布局子视图一样*调整图片和文字的位置,简单方便。可以调出需要的任意布局方式。

代码如下:

1.在.h文件中:

自定义类ZFButton,继承自UIButton。定义枚举ZFButtonType说明不同的类型。定义实例更新方法- (void)updateButtonStyleWithType:在需要的时候,根据自己的意愿更新成自己想要的样式。

#import <UIKit/UIKit.h>

typedef enum : NSUInteger {
ZFButtonTypeCenterImageCenterTitle,//图片,文字都居中
ZFButtonTypeRightImageLeftTitle,//图片右,文字左
ZFButtonTypeLeftImageNoneTitle,//图片左,文字无
} ZFButtonType; @interface ZFButton : UIButton
+ (instancetype)zfButtonWithType:(ZFButtonType)buttonType; - (void)updateButtonStyleWithType:(ZFButtonType)buttonType;
@end

2.中.m文件中:

重写方法- (void)layoutSubviews,根据不同的类型生成不同的布局。

- (void)layoutSubviews {
[super layoutSubviews]; if (self.type == ZFButtonTypeCenterImageCenterTitle) {
[self resetBtnCenterImageCenterTitle];
} else if (self.type == ZFButtonTypeLeftImageNoneTitle) {
[self resetBtnLeftImageNotTitle];
} else if (self.type == ZFButtonTypeRightImageLeftTitle) {
[self resetBtnRightImageLeftTitle];
}
}

工厂方法zfButtonWithType:创建不同类型的ZFButton。

实例更新方法- (void)updateButtonStyleWithType:更新成不同UI类型的Button

+ (instancetype)zfButtonWithType:(ZFButtonType)buttonType {

    ZFButton * btn = [ZFButton buttonWithType:UIButtonTypeCustom];
btn.type = buttonType; return btn;
} - (void)updateButtonStyleWithType:(ZFButtonType)buttonType { self.type = buttonType;
[self layoutSubviews];
}

具体算法如下:

#pragma mark - 私有方法
/*!**方式二***/
- (void)resetBtnCenterImageCenterTitle { self.imageView.frame = self.bounds;
[self.imageView setContentMode:UIViewContentModeCenter]; self.titleLabel.frame = self.bounds;
self.titleLabel.textAlignment = NSTextAlignmentCenter;
} - (void)resetBtnLeftImageNotTitle { CGRect frame = self.bounds;
frame.size.width *= 0.5;
self.imageView.frame = frame;
[self.imageView setContentMode:UIViewContentModeCenter]; self.titleLabel.frame = CGRectZero;
self.titleLabel.textAlignment = NSTextAlignmentCenter;
} - (void)resetBtnRightImageLeftTitle { CGRect frame = self.bounds;
frame.size.width *= 0.5;
self.titleLabel.frame = frame;
self.titleLabel.textAlignment = NSTextAlignmentCenter; frame.origin.x = (self.bounds.size.width - frame.size.width);
self.imageView.frame = frame;
[self.imageView setContentMode:UIViewContentModeCenter];
}

效果图和层级图展示如下:

UIButton图片文字控件位置自定义(图片居右文字居左、图片居中文字居中、图片居左文字消失等)UIButton图片文字控件位置自定义(图片居右文字居左、图片居中文字居中、图片居左文字消失等)