一. 自定义一个带有六个框的view
1. 边框
1 2
| self.layer.borderColor = [UIColor blackColor].CGColor self.layer.borderWidth = 1
|
2. 重写- (void)drawRect:(CGRect)rect方法画竖线
1 2 3 4 5 6 7 8 9 10 11 12
| - (void)drawRect:(CGRect)rect{ CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(context, 1); CGContextSetRGBStrokeColor(context, 0, 0, 0, 1); CGContextBeginPath(context); 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); }
|
二. 使用UITextFieldView接受用户输入,增加点击事件开启键盘,
1 2 3 4 5 6 7 8 9
| - (UITextField *)textfield{ if (!_textfield) { _textfield = [[UITextField alloc] init]; _textfield.delegate = self; _textfield.keyboardType = UIKeyboardTypeNumberPad; [_textfield addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventEditingChanged]; } return _textfield; }
|
1 2 3
| UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickAction)]; [self addGestureRecognizer:tap];
|
1 2 3
| - (void)clickAction { [self.textfield becomeFirstResponder]; }
|
三. 在设置frame后,增加6个label显示输入
**一定要在view设置frame后,初始化label,否则labelframe为CGRectZero;
1 2 3 4 5 6 7 8 9 10
| - (void)setUpLabels { 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 = 600 + i; label.textColor = [UIColor colorWithRGBHex:0x333333]; label.font = [UIFont customBoldFontWithSize:34]; [self addSubview:label]; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| @interface CustomSixPasswordInputView
@property (nonatomic, copy) NSString *oldText;
@end
...
- (void)valueChange:(UITextField *)textField{ NSString *text = textField.text; BOOL isDelete = self.oldText.length > text.length; if (text.length <= 6) { for (int i = 0; i < 6; i++) { UILabel *label = (UILabel *)[self viewWithTag:600 + i]; if (i < text.length) { if (!isDelete && i == text.length - 1) { label.text = [text substringWithRange:NSMakeRange(text.length - 1, 1)]; } else { label.text = @"*"; } } else { label.text = @""; } } } else { textField.text = [text substringWithRange:NSMakeRange(0, 6)]; } if ([self.delegate respondsToSelector:@selector(inputText:)]) { [self.delegate inputText:self.textfield.text]; } self.oldText = textField.text; }
|
