IOS开发-六位密码输入框
2017-12-18 本文已影响297人
ZAREMYDREAM
- 现在app中时常用到六位密码,而这种密码输入框则需要我们自己来编写。
实现
六位密码框并不是一个被分成六格的textfield,而是由一个隐藏的textfield与六个label实现。其原理主要是通过监控textfield里面值的变化,从而动态改变label的值,而形成输入了值的假象。
1、UITextField定义
- (UITextField *)pswTF{
if (!_pswTF) {
_pswTF = [[UITextField alloc] init];
_pswTF.delegate = self;
_pswTF.keyboardType = UIKeyboardTypeNumberPad;
//添加对输入值的监视
[_pswTF addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventEditingChanged];
}
return _pswTF;
}
2、添加点击事件,使点击输入框开启键盘
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click)];
[self addGestureRecognizer:tap];
3、添加label与分割线的绘制
#pragma mark - 设置UI
- (void)initUI{
self.backgroundColor = [UIColor whiteColor];
[self addSubview:self.pswTF];
//添加6个label
for (int i = 0; i < 6; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(i*self.frame.size.width/6.0, 0, self.frame.size.width/6.0, self.frame.size.height)];
label.textAlignment = NSTextAlignmentCenter;
label.tag = 100 + i;
[self addSubview:label];
}
//设置边框圆角与颜色
self.layer.masksToBounds = YES;
self.layer.cornerRadius = 10.0;
self.layer.borderColor = [UIColor blackColor].CGColor;
self.layer.borderWidth = 2;
}
//划线
- (void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2);
//设置分割线颜色
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1);
CGContextBeginPath(context);
//5条分割线绘制
for (int i = 0; i < 5; i++){
CGContextMoveToPoint(context, self.frame.size.width/6.0 * (i + 1), 0);
CGContextAddLineToPoint(context,self.frame.size.width/6.0 * (i + 1) , self.frame.size.height);
}
CGContextStrokePath(context);
}
4、监控textfield值,改变label
- (void)valueChange:(UITextField *)textField{
NSString *text = textField.text;
if (text.length <= 6){ //当输入小于6的时候
for (int i = 0; i < 6; i++) {
//通过tag获取label
UILabel *label = (UILabel *)[self viewWithTag:100 + i];
//更改label值
if (i < text.length) {
label.text = @"*";
}
else{
label.text = @"";
}
}
}
else{ //输入值长度大于6时,截取字符串
textField.text = [text substringWithRange:NSMakeRange(0, 6)];
}
NSLog(@"%@",textField.text);
}
5、返回密码
- (NSString *)getPsw{
return self.pswTF.text;
}
- 这样六位密码输入框就实现了,具体可以查看我的DEMO