經過繼承UIButton 重寫LayoutSubViews實現
.h文件以下ide
#import <UIKit/UIKit.h>atom
typedef NS_ENUM(NSInteger, UIMyDefindButtonImageType) {.net
UIMyDefindButtonImageTypeNormal = 0,//系統默認類型 左圖片 右文字code
UIMyDefindButtonImageTypeTop,//上圖片 下文字orm
UIMyDefindButtonImageTypeRight,//右圖片 左文字繼承
UIMyDefindButtonImageTypeBottom//下圖片 上文字圖片
};get
@interface MyDefindButton : UIButtonanimation
@property (nonatomic,assign) UIMyDefindButtonImageType myDefindType;it
.m文件以下
#import "MyDefindButton.h"
#define Jianju 2 //圖片和文字之間的間距
@implementation MyDefindButton
- (void)layoutSubviews{
[super layoutSubviews];
CGRect titleF = self.titleLabel.frame;
CGRect imageF = self.imageView.frame;
switch (self.myDefindType) {
case UIMyDefindButtonImageTypeNormal:
break;
case UIMyDefindButtonImageTypeTop:{
CGRect newImageRect;
newImageRect.origin.x = self.width/2-(imageF.size.width/2);
newImageRect.origin.y = self.height/2 - ((imageF.size.height+Jianju+titleF.size.height)/2);
newImageRect.size.width = imageF.size.width;
newImageRect.size.height = imageF.size.height;
self.imageView.frame = newImageRect;
self.titleLabel.frame = CGRectMake(self.width/2-(titleF.size.width/2), self.imageView.bottom+Jianju, titleF.size.width, titleF.size.height);
}
break;
case UIMyDefindButtonImageTypeRight:{
titleF.origin.x = self.width/2-((titleF.size.width + imageF.size.width+Jianju)/2);
self.titleLabel.frame = titleF;
imageF.origin.x = CGRectGetMaxX(titleF) + 3;
self.imageView.frame = imageF;
}
break;
case UIMyDefindButtonImageTypeBottom:{
CGRect newTitleRect;
newTitleRect.origin.x = self.width/2-(titleF.size.width/2);
newTitleRect.origin.y = self.height/2 - ((imageF.size.height+Jianju+titleF.size.height)/2);
newTitleRect.size.width = titleF.size.width;
newTitleRect.size.height = titleF.size.height;
self.titleLabel.frame = newTitleRect;
self.imageView.frame = CGRectMake(self.width/2-(imageF.size.width/2), self.titleLabel.bottom+Jianju, imageF.size.width, imageF.size.height);
}
break;
default:
break;
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/