it-swarm.com.ru

Как я могу ограничить специальные символы в UITextField, кроме точки и подчеркивания?

Как я могу ограничить специальные символы в UITextField кроме точки и подчеркивания? 

Я попробовал фрагмент кода ниже, но без удачи:

#define ACCEPTABLE_CHARECTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
         NSCharacterSet *acceptedInput = [NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS];
        if (![[string componentsSeparatedByCharactersInSet:acceptedInput] count] > 1){
            NSLog(@"not allowed");
            return NO;
        }
        else{
            return YES;
        }
}
28
Graham Bell

Попробуйте блок кода, приведенный ниже, он работал нормально для меня.

Swift 3.0

let ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let cs = NSCharacterSet(charactersIn: ACCEPTABLE_CHARACTERS).inverted
    let filtered = string.components(separatedBy: cs).joined(separator: "")

    return (string == filtered)
}

Цель C

#define ACCEPTABLE_CHARACTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
      NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];

      NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

      return [string isEqualToString:filtered];
}

Надеюсь, это сработает и для вас.

90
Mrunal

Попробуй это

NSCharacterSet  *set= [NSCharacterSet symbolCharacterSet];
if ([string rangeOfCharacterFromSet:[set invertedSet]].location == NSNotFound) {
    // valid
} else {
    // invalid
}

вы можете сделать свой собственный набор с 

NSCharacterSet  *set= [NSCharacterSet characterSetWithCharactersInString:@"<all your symbols you want to ignore>"];
4
amar

Swift 2.2 основан на ответ Мрунала :

let notAllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.";
func textField(
    textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String)
    -> Bool
{
    let set = NSCharacterSet(charactersInString: notAllowedCharacters);
    let inverted = set.invertedSet;

    let filtered = string
        .componentsSeparatedByCharactersInSet(inverted)
        .joinWithSeparator("");
    return filtered == string;

}
3
Evdzhan Mustafa

NSString *Regex = @"[A-Za-z0-9^]*";

NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];

[TestResult evaluateWithObject:@"YourTestString"]; 

Последнее возвращаемое логическое значение true/false

В методе

+ (BOOL) validateSpecialCharactor: (NSString *) text {
NSString *Regex = @"[A-Za-z0-9^]*";
NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
return [TestResult evaluateWithObject:text];
}
3
Indra

Решение Swift 3.1


let ACCEPTABLE_CHARACTERS = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let cs = CharacterSet(charactersIn: ACCEPTABLE_CHARACTERS).inverted
        let filtered: String = (string.components(separatedBy: cs) as NSArray).componentsJoined(by: "")
        return (string == filtered)
    }
2
Sourabh Sharma

Это может помочь вам попробовать это .. и дайте мне знать, пожалуйста

-(BOOL)isHaveSpecialChar:(NSString*)str{
NSString *customStr = @"~`[email protected]#$%^&*()+=-/;:\"\'{}[]<>^?, ";
NSCharacterSet *alphaSet = [NSCharacterSet characterSetWithCharactersInString:customStr];
BOOL isHaveSpecialChar = [[str stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
return !isHaveSpecialChar;
}
1
SachinVsSachin

Swift 4

let RISTRICTED_CHARACTERS = "'*=+[]\\|;:'\",<>/?%"

Метод делегата UITextField:

func textField(_ textField: UITextField, shouldChangeCharactersIn _: NSRange, replacementString string: String) -> Bool {
    let set = CharacterSet(charactersIn: RISTRICTED_CHARACTERS)
    let inverted = set.inverted
    let filtered = string.components(separatedBy: inverted).joined(separator: "")
    return filtered != string
}
1
Sunil Targe
func  textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let set = NSCharacterSet(charactersIn: "0123456789")
    let inverted = set.inverted;

    let filtered = string.components(separatedBy: inverted).joined(separator: "")
    return filtered == string;
0
GOWTHAM