iOS技术文章iOS开发点滴

ios OC 输入框禁止输入空格/去掉空格/只能输入字母和数字

2017-10-13  本文已影响56人  墨竹AI

1 输入框禁止输入空格

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];
    if (![string isEqualToString:tem]) {
        return NO;
    }
    return YES;
}

2 去掉字符串中的空格

 [x stringByReplacingOccurrencesOfString:@" " withString:@""];

3 限制输入框只能输入字母和数字

//定义数字和字母的宏
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
      //只能输入数字和字母
      NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
      NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

      if (![string isEqualToString:filtered])
       {
           return NO;
       }

      return YES;
}

上一篇 下一篇

猜你喜欢

热点阅读