-1

I'm working on a social script for iOS but i'll need my username login only be lowercase. I've got the string where lowercaseString needs to be into but I don't exactly know where.

So this is the code:

NSString *username = [self.usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];**

Where do I put the .lowercaseString for only lowercase login?

Valentin Lorentz
  • 9,556
  • 6
  • 47
  • 69
SnDer
  • 1
  • 4

2 Answers2

0
NSString *username = [self.usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].lowercaseString;

However, this only ensures that username is lowercase. To make sure that the UITextField contains only lowercase characters, you may do this:

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


   NSRange upperCharRange;
   upperCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]];

   if (uppercaseCharRange.location != NSNotFound) {

        textField.text = [textField.text stringByReplacingCharactersInRange:range
                                                             withString:[string lowercaseString]];
        return NO;
    }

    return YES;
}

This method is only called if you add <UITextFieldDelegate> to the .h file of your class. You also need to set the delegate of your UITextField instance to self of your class instance, like so:

textField.delegate = (id <UITextFieldDelegate>)mainViewController;
John
  • 8,468
  • 5
  • 36
  • 61
  • Still can use capital letters after this.. :( – SnDer May 17 '15 at 10:12
  • The variable `username` will be lowercase. The text field will still be upper case letters if the user types upper case letters. Do you want to show it only lower-case letters? – John May 17 '15 at 10:14
  • I've added a solution above that ensures that the text field contains only lowercase characters. – John May 17 '15 at 10:20
  • This code will fail if the user pastes in text that contains two or more ranges of uppercase letters. – rmaddy May 17 '15 at 15:19
  • I don't see how; the entire `string` is lowercased. – Steven Fisher Oct 17 '16 at 20:26
0

You can put it after self.usernameField.text or after the ]]. There is not really any difference since lowerCase does not affect whitespaces or newline characters.

The only difference is that after trimming the string, the string might be shorter and therefore the transformation to a lower case string will take less time (not noticeably though).

Therefore I would propose adding it after ]]:

NSString *username = [self.usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].lowercaseString;
luk2302
  • 55,258
  • 23
  • 97
  • 137