按钮设置title和image默认格式就是图片在左文字向右 开发中往往不尽人意
[but setTitle:[_dateForm stringFromDate:[NSDate date]] forState:UIControlStateNormal];
[but setImage:[UIImage imageNamed:@"xiala"] forState:UIControlStateNormal];
可以通过重写UIButton的LayoutSubViews来改成我们希望看到的布局
创建继承UIButton子类
.h文件如下
#importtypedef NS_ENUM(NSInteger, UIMyDefindButtonImageType) {
UIMyDefindButtonImageTypeNormal = 0,//系统默认类型 左图片 右文字
UIMyDefindButtonImageTypeTop,//上图片 下文字
UIMyDefindButtonImageTypeRight,//右图片 左文字
UIMyDefindButtonImageTypeBottom//下图片 上文字
};
@interface MyDefindButton : UIButton
@property (nonatomic,assign) UIMyDefindButtonImageType myDefindType;
@end
.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;
}
}