在前三篇1 、2、3中,已经实现了输入框的效果和键盘输入,接下来,要完善一下细节。
限制属性的范围
为了避免设置的属性过于奇葩而造成的界面错乱,需要限制一些属性的取值范围:
//圆点的半径大小,不超过每个格子的大小
@property (nonatomic,assign) IBInspectable CGFloat dotRadius;
-(void)setDotRadius:(CGFloat)dotRadius{
float max = [self getMinBoxSide];
if (dotRadius > max) {
dotRadius = max;
}
_dotRadius = dotRadius;
}
//可以输入几位数(范围为1~9,超出范围无效)
@property (nonatomic,assign) IBInspectable NSInteger boxCount;
-(void)setBoxCount:(NSInteger)boxCount{
if (boxCount<1) {
boxCount = 1;
}else if(boxCount>9){
boxCount = 9;
}
_boxCount = boxCount;
}
//输入框的圆角半径,不超过最短边的一半
@property (nonatomic,assign) IBInspectable CGFloat boxRadius;
-(void)setBoxRadius:(CGFloat)boxRadius{
float max = [self getMinBoxSide]/2;
if (boxRadius > max) {
boxRadius = max;
}
_boxRadius = boxRadius;
}
增加一些功能
增加明文显示
//是否为密码输入框,为YES时显示圆点,默认为YES
@property (nonatomic,assign) IBInspectable BOOL secureTextEntry;
// 设置文本字号 默认17
@property (nonatomic,assign) IBInspectable CGFloat fontSize;
// 设置文本字体 默认系统字体17号
@property (nonatomic,strong) UIFont *font;
//设置文本颜色,默认为黑色。
@property (nonatomic,strong) IBInspectable UIColor *textColor;
-(void)setFontSize:(CGFloat)fontSize{
_fontSize = fontSize;
self.font = [UIFont systemFontOfSize:fontSize];
}
/**
* 绘制文字
* context 上下文
* rect
**/
-(void)drawString:(CGContextRef)context
rect:(CGRect)rect{
if ([self hasText] == NO) {
return;
}
NSMutableString *str = [NSMutableString stringWithString:_text];
for (int i = 0; i < _text.length; i++) {
NSDictionary *attr = @{NSForegroundColorAttributeName:[_textColor colorWithAlphaComponent:[self.dotAlphas[i] floatValue]],
NSFontAttributeName: self.font};
CGRect strRect = [self getBoxRect:i size:rect.size];
//获取字符
NSString *subString = [str substringWithRange:NSMakeRange(i, 1)];
//计算文字大小
CGSize textSize = [subString sizeWithAttributes:attr];
//计算绘制区间
CGRect drawRect = CGRectInset(strRect,(strRect.size.width - textSize.width) / 2,(strRect.size.height - textSize.height) / 2);
//绘制文字
[subString drawInRect:drawRect withAttributes:attr];
}
}
-(void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();
//调整位置,因为边框如果超出rect会被截取
CGRect bounds = CGRectInset(rect, _borderWidth * 0.5, _borderWidth * 0.5);
[self drawBorder:context rect:bounds];
//判断是否明文显示
if (_secureTextEntry) {
[self drawDot:context rect:bounds];
}else{
[self drawString:context rect:bounds];
}
}
加上代理方法
@class GZCPasswordView;
@protocol GZCPasswordViewDelegate <NSObject>
@optional
// 是否能够被改变
-(BOOL)passwordView:(GZCPasswordView *)passwordView shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)text;
// 内容改变后
-(void)passwordViewDidChangedText:(GZCPasswordView *)passwordView;
// 当输入完成后,是否需要自动取消第一响应者,返回YES则收起键盘(如果有的话)。默认为返回 NO。
-(BOOL)passwordViewDidFullText:(GZCPasswordView *)passwordView;
@end
以上,这个自定义控件就基本完成了。
代码在GZCPasswordView
网友评论