问题描述
卡号的前12位数字应为安全的输入,其余4位作为正常输入,例如,我正在输入卡号-4111 1111 11111111.在文本字段中输入此文本时,前12位数字应为安全输入,而后4位应为作为常规条目,即1111.(最终卡号应类似于XXXXXXXXXXXX1111).
Card number first 12 digits should be secure entry and remaining 4 digits as normal for example i am entering card number - 4111 1111 1111 1111. While entering this text in textfield first 12 digits should be secure entry and last 4 digits should be as normal entry i.e., 1111.(finally card number will looks like XXXXXXXXXXXX1111).
任何人都可以解释一下该怎么做.
Can any one explain me how to do it.
推荐答案
一个选项是实现UITextField
委托方法textField:shouldChangeCharactersInRange:replacementString:
.在这种方法中,您将始终希望返回NO.但是首先,您需要更新文本字段的文本,以使前12位数字显示为X.您需要在另一个ivar中跟踪实际文本.
One option is to implement the UITextField
delegate method textField:shouldChangeCharactersInRange:replacementString:
. In this method you would want to always return NO. But first you would update the text field's text such that the first 12 digits show an X. You would keep track of the actual text in another ivar.
这应该起作用:
- (NSString *)maskNumber:(NSString *)num {
static NSString *twelveX = @"XXXXXXXXXXXX";
if (num.length < twelveX.length) {
return [twelveX substringToIndex:num.length];
} else {
return [twelveX stringByAppendingString:[num substringFromIndex:twelveX.length]];
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Determine where the cursor should be
UITextRange *selRange = textField.selectedTextRange;
NSInteger cursorPos = [textField offsetFromPosition:textField.beginningOfDocument toPosition:selRange.start] + string.length;
_cardNum = [_cardNum stringByReplacingCharactersInRange:range withString:string];
textField.text = [self maskNumber:_cardNum];
// Reset the cursor position
UITextPosition *startPos = [textField positionFromPosition:textField.beginningOfDocument offset:cursorPos];
selRange = [textField textRangeFromPosition:startPos toPosition:startPos];
textField.selectedTextRange = selRange;
return NO;
}
其中,_cardNum
是类型为NSString
的ivar.这会跟踪实际的卡号.
where _cardNum
is an ivar of type NSString
. This tracks the actual card number.
这篇关于卡号的前12位数字应安全输入,其余4位数字正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!