Do a format bank card today,Avoid rebuilding wheels,I looked for Du Niang,Seeing a good implementation,record it,And comes with implementation ideas

#pragma mark-uitextfielddelegate called after typing characters in uitextfield
-(bool) textfield:(uitextfield *) textfield shouldchangecharactersinrange:(nsrange) range replacementstring:(nsstring *) string {
 // Get the string before the change
 nsstring * text=[textfield text];
 // Type the character set,\ b indicates delete key
 nscharacterset * characterset=[nscharacterset charactersetwithcharactersinstring:@"0123456789 \ b"];
 // Perform space filtering on the currently typed characters
 string=[string stringbyreplacingoccurrencesofstring:@"" withstring:@""];
 // invertedset will invert the current result set,Checks if the currently typed character is in the character set,If not, return no directly without changing the textfield value
 if ([string rangeofcharacterfromset:[characterset invertedset]]. location!=nsnotfound) {
 return no;
 // Increase the end of the string before the currently typed character is changed
 text=[text stringbyreplacingcharactersinrange:range withstring:string];
 // Confirm again to remove spaces from the string
 text=[text stringbyreplacingoccurrencesofstring:@"" withstring:@""];
 // Init character is used to save the formatted string
 nsstring * newstring [email protected]"";
 // while format the text
 while (text.length>0) {
 // Truncate by 4 characters,If the current character is less than 4 digits, it is truncated according to the maximum length of the current string
 nsstring * substring=[text substringtoindex:min (text.length, 4)];
 // Put the intercepted characters into the string that needs to be formatted
 newstring=[newstring stringbyappendingstring:substring];
 if (substring.length == 4) {
  // The length of the intercepted string is 4 digits, and a space character is added at the end
  newstring=[newstring stringbyappendingstring:@""];
 // Truncate the string from text and remove
 text=[text substringfromindex:min (text.length, 4)];
 // Confirm again to filter out characters other than the specified character
 newstring=[newstring stringbytrimmingcharactersinset:[characterset invertedset]];
 // Domestic bank cards are usually 16 to 19 digits. 4 spaces are added after formatting, which is a maximum of 23 characters.
 if (newstring.length>23) {
 return no;
 // Manually assign a value to the textfield
 [textfield settext:newstring];
 // Returns no to automatically add characters after the current character without delegation,Achieve formatting effect
 return no;
  • Previous Introduction and examples of several types of TIMESTAMP in Oracle
  • Next Solution of the drop-down menu does not appear after the BootStrap drop-down menu is clicked (the drop-down menu does not pop up