UITextField没有最大字符限制的空格

时间:2013-03-13 00:20:24

标签: ios uitextfield whitespace uitextfielddelegate maxlength

我有两个UITextField:usernameField& passwordField。对于这两个字段,我正在尝试实现下面的代码,不允许用户键入任何空格(使用空格键)并限制每个文本字段的最大长度。白色空间的代码工作正常,但最大长度失败。

//Addressing White space and length in the form
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if  ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound)      {
    return YES;
}  else  {
    self.title.text = @"No Spaces Allowed";
    self.title.textColor = [UIColor yellowColor];
    return NO;
}


if (textField == self.usernameField)
{
    NSInteger MAXLENGTH = 15;

    NSUInteger oldLength = [textField.text length];
    NSUInteger replacementLength = [string length];
    NSUInteger rangeLength = range.length;

    NSUInteger newLength = oldLength - rangeLength + replacementLength;

    BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;

    return newLength <= MAXLENGTH || returnKey;

if (textField == self.passwordField)
    {
        NSInteger MAXLENGTH = 10;

        NSUInteger oldLength = [textField.text length];
        NSUInteger replacementLength = [string length];
        NSUInteger rangeLength = range.length;

        NSUInteger newLength = oldLength - rangeLength + replacementLength;

        BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
        return newLength <= MAXLENGTH || returnKey;   
    }
}
}

1 个答案:

答案 0 :(得分:1)

允许最多字符数和拒绝空格

实施 shouldChangeCharactersInRange 委托

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    BOOL _isAllowed = YES;

    NSString *tempString = [[textField.text stringByReplacingCharactersInRange:range withString:string] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


    if ([self.yourTextFeildName.text isEqualToString:tempString] || [tempString length] > 5)
    {
        _isAllowed =  NO;
    }

    return   _isAllowed;
}

最少字符

实施 textFieldDidEndEditing 委托

- (void)textFieldDidEndEditing:(UITextField *)textField
{
   if ([textField.text length] < 5)
   {
         //text field length is less than 5.
   }
}