在开发中常常会碰到须要对按钮中的图片文字位置作调整的需求。
第一种方式是经过设置按钮中图片文字的偏移量。经过方法setTitleEdgeInsets和setImageEdgeInsets实现算法
代码以下:布局
/*!**方式一***/ - (void)updateBtnStyle_rightImage:(UIButton *)btn { CGFloat btnImageWidth = btn.imageView.bounds.size.width; CGFloat btnLabelWidth = btn.titleLabel.bounds.size.width; CGFloat margin = 3; btnImageWidth += margin; btnLabelWidth += margin; [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -btnImageWidth, 0, btnImageWidth)]; [btn setImageEdgeInsets:UIEdgeInsetsMake(0, btnLabelWidth, 0, -btnLabelWidth)]; }
这种方式对普通的需求是能够知足的,可是操做起来麻烦,不是那么直观。对于像修改图片子控件的宽高这种高度自定义的行为是很难实现的。spa
第二种方式则能够像布局子视图同样自由调整图片和文字的位置,简单方便。能够调出须要的任意布局方式。code
代码以下:blog
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,根据不一样的类型生成不一样的布局。it
- (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。class
实例更新方法- (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]; }
效果图和层级图展现以下: