自定义按钮,图片在上或者图片在右(纯代码或者XIB)
项目中经常出现按钮的图片在上或者图片在右的情况 ,所以特意封了一个类来控制,,废话少说,直接上代码:
1.先说纯代码的情况,新建一个类继承UIButton,
.h文件
#import
typedefNS_ENUM(NSInteger,ButtonType) {
imageRightType,//图片在右
imageTopType,//图片在上
};
NS_ASSUME_NONNULL_BEGIN
@interface JXBCustomButton : UIButton
-(id)initWithFrame:(CGRect)frame andButtonType:(ButtonType )type;
@end
NS_ASSUME_NONNULL_END
.m文件
#import "JXBCustomButton.h"
@interface JXBCustomButton(){
ButtonType_type;
}
@end
@implementation JXBCustomButton
- (void)layoutSubviews
{
[super layoutSubviews];
if (_type==imageTopType) {
CGRecttitleLabelFrame =self.titleLabel.frame;
CGRectimageViewFrame =self.imageView.frame;
self.titleLabel.textAlignment = NSTextAlignmentCenter;
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
titleLabelFrame.origin.x= (self.frame.size.width- titleLabelFrame.size.width)/2;
titleLabelFrame.origin.y=self.frame.size.height*0.6;
self.titleLabel.frame= titleLabelFrame;
if(titleLabelFrame.size.width< imageViewFrame.size.width) {
imageViewFrame.origin.x= imageViewFrame.origin.x;
}else{
imageViewFrame.origin.x= titleLabelFrame.origin.x+ (titleLabelFrame.size.width- imageViewFrame.size.width)/2;
}
imageViewFrame.origin.y-=4;
self.imageView.frame= imageViewFrame;
}else{
/** 修改 title 的 frame */
CGRectimageViewFrame =self.imageView.frame;
CGRecttitleLabelFrame =self.titleLabel.frame;
titleLabelFrame.origin.x= (self.frame.size.width- titleLabelFrame.size.width- imageViewFrame.size.width)/2;;
self.titleLabel.frame= titleLabelFrame;
imageViewFrame.origin.x= titleLabelFrame.origin.x+ titleLabelFrame.size.width+4;//titleLabelFrame.size.width+4;
self.imageView.frame= imageViewFrame;
}
}
-(id)initWithFrame:(CGRect)frame andButtonType:(ButtonType )type
{
if(self=[superinitWithFrame:frame]) {
_type= type;
}
return self;
}
@end
此类只针对如题所说的2种情况,,常规的按钮图片在左就不用说了,按钮图片在下也可以按代码逻辑来推写,因为项目目前没遇到,就没写。。
2.xib来控制百度文章就很多了,比较简单。大概就是如图这种。