Xcode의 TextField 사용할때 특정 문자만 입력 받도록 하기 위해서는 다음과 같이 한다.
예) 숫자와 영문자만 입력 받기
#define LEGAL_TEXT @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz " - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:LEGAL_TEXT] invertedSet]; NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return [string isEqualToString:filtered]; }
예2) 숫자와 소수점만 입력 받기 (소수점이 입력된 뒤에는 숫자만 입력 받는다)
키패드 타입을 변경
entryField.keyboardType = UIKeyboardTypeNumbersAndPunctuation; #define NUMBERS @"0123456789" #define NUMBERSPERIOD @"0123456789." - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSCharacterSet *cs; NSString *filtered; // Check for period if ([entryField.text rangeOfString:@"."].location == NSNotFound) { cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERSPERIOD] invertedSet]; filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return [string isEqualToString:filtered]; } // Period is in use cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet]; filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return [string isEqualToString:filtered]; }
[출처] http://comxp.tistory.com/250