项目需求:
IMG_0411.PNG输入身份证号,需要X这个东西,只能自己写了。
构建这个输入视图简单,各个按钮配置Tag即可。
每个按钮需要添加两个点击事件:touchUpInside 和touchDown。
设置self.TextFieldNo.inputView = self.customKeyView即可。
关键是处理点击事件:
#pragma mark - 点击键盘数字
- (void)numberClick:(UIButton *)btn {
if (btn.tag == 10 || btn.tag == 12) {
btn.backgroundColor = [UIColor colorWithHexString:@"#D1D5DB"];
}else{
btn.backgroundColor = [UIColor colorWithHexString:@"#FFFFFF"];
}
UIButton *selectedB = btn;
self.TextFieldNo.textColor = [UIColor colorWithHexString:@"#2D2D2D"];
//删除键
if (selectedB.tag == 12) {
if (self.TextFieldNo.text.length > 0) {
//需要考虑光标位置
NSInteger location = [self selectedRange].location;
NSInteger newLocation = location;
NSInteger foreLocation = location-1;
NSString *oneString,*twoString;
if (foreLocation >= 0) {
oneString = [self.TextFieldNo.text substringToIndex:foreLocation];
twoString = [self.TextFieldNo.text substringFromIndex:location];
newLocation = foreLocation;
}else{
twoString = self.TextFieldNo.text;
}
if (oneString.length == 0) {
oneString = @"";
}
if (twoString.length == 0 ) {
twoString = @"";
}
NSString *newString = [NSString stringWithFormat:@"%@%@",oneString,twoString];
self.TextFieldNo.text = newString;
[self setSelectedRange:NSMakeRange(newLocation, 0)];
}
}else {
//需要考虑用户滑动光标的操作,不能直接添在最后一位
NSString *newString = selectedB.titleLabel.text;
NSInteger location = [self selectedRange].location;
NSMutableString *allString = [NSMutableString stringWithFormat:@"%@",self.TextFieldNo.text];
[allString insertString:newString atIndex:location];
self.TextFieldNo.text = allString;
[self setSelectedRange:NSMakeRange(location+1, 0)];
}
}
//获取当前range
-(NSRange)selectedRange{
NSInteger location = [self.TextFieldNo offsetFromPosition:self.TextFieldNo.beginningOfDocument toPosition:self.TextFieldNo.selectedTextRange.start];
NSInteger length = [self.TextFieldNo offsetFromPosition:self.TextFieldNo.selectedTextRange.start toPosition:self.TextFieldNo.selectedTextRange.end];
return NSMakeRange(location, length);
}
//设置range
- (void) setSelectedRange:(NSRange) range
{
UITextPosition* beginning = self.TextFieldNo.beginningOfDocument;
UITextPosition* startPosition = [self.TextFieldNo positionFromPosition:beginning offset:range.location];
UITextPosition* endPosition = [self.TextFieldNo positionFromPosition:beginning offset:range.location + range.length];
UITextRange* selectionRange = [self.TextFieldNo textRangeFromPosition:startPosition toPosition:endPosition];
[self.TextFieldNo setSelectedTextRange:selectionRange];
}
//点击按下后变色
- (void)numberTouchDown:(UIButton*)sender
{
if (sender.tag == 10 || sender.tag == 12) {
sender.backgroundColor = [UIColor colorWithHexString:@"#FFFFFF"];
}else{
sender.backgroundColor = [UIColor colorWithHexString:@"#D1D5DB"];
}
}
加油~
网友评论