Iphone – Remove WhiteSpace from start of uitextfield

ios5iphoneuitextfield

I want to remove white space from start of word. i.e my first character should not be space and having only one space in between two words .I am trying lots of things but not able to remove space from starting.

My code is:

controller.h

int whitespaceCount;

controller.m

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    if ([string rangeOfCharacterFromSet:whitespace].location != NSNotFound)
    {
        whitespaceCount++;
        if (whitespaceCount > 1)
        {
            return NO;
        }
    }
    else
    {
        whitespaceCount = 0;
        return YES;
    }
}

from above code one space between two words are works perfectly. Please suggest me how i remove starting space. Thanks in advance.

Best Answer

you can do with method :-

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if (range.location == 0 && [string isEqualToString:@" "]) {
        return NO;
    }
    return YES;
} 

Or For latest Swift, you can use following:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if range.location == 0 && (string == " ") {
        return false
    }
    return true
}

using this you cannot able To enter whitescpace at starting.

and you can do also like that:-

 NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];

if you want to remove it from your string , you need to work on following

NEW STRING> = [<STRING_CONTAINS WHITESPACE> stringByTrimmingCharactersInSet:whitespace];
 NSLog("String without white space = %@",NEW STRING);

Or if you want to remove whitespace entirely from the textfield use following:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if (string == " ") {
        return false
    }
    return true
}

And to make this method work, make sure to mark your textfield.delegate = self

Related Topic