自定义按钮,即自定义按钮中的文字和图标。
自定义一个继承自UIButton
的类,重写父类的一些方法:
代码如下:
.h
文件
#import <UIKit/UIKit.h>
@interface SStiBtn : UIButton
@end
.m
文件
#import "SStiBtn.h"
@implementation SStiBtn
-(instancetype)initWithFrame:(CGRect)frame{
self=[super initWithFrame:frame];
if (self) {
self.imageView.contentMode=UIViewContentModeCenter;
self.titleLabel.textAlignment=NSTextAlignmentRight
;
[self.titleLabel setTextColor:[UIColor purpleColor]];
}
return self;
}
//设置内部图标的frame
-(CGRect)imageRectForContentRect:(CGRect)contentRect{
CGFloat imageY=0;
CGFloat imageW=self.height;
CGFloat imageH=self.height;
CGFloat imageX=self.width-imageW;
return CGRectMake(imageX, imageY, imageW, imageH);
}
//设置内部文字的frame
-(CGRect)titleRectForContentRect:(CGRect)contentRect{
CGFloat titleX=0;
CGFloat titleY=0;
CGFloat titleH=self.height;
CGFloat titleW=self.width-self.imageView.width;
return CGRectMake(titleX, titleY, titleW, titleH);
}
@end