Quick and Easy Password Field

You don’t even need to subclass NSTextField (or it’s mobile counterpart) with this dirty trick. All you do is save the password somewhere else, and set it to a mask of *’s when you finish editing. All you need is a global NSString called password and a few IBActions.


- (NSString *)username { return [userField text]; }
- (NSString *)password { return password; }

- (IBAction)editingEnded:(id)sender {
        NSString *oldtext = passField.text;
        int len = (oldtext) ? [oldtext length] : 0;
        int i;
        NSString *mask = @"";
        for (i = 0; i < len; i++) {
                mask = [mask stringByAppendingString:@"*"];
        }
        if (password) { [password release]; password = nil; }
        password = oldtext;
        [password retain];
        passField.text = mask;
}

- (IBAction)editingBegan:(id)sender {
        passField.text = password;
}

Cool, no? You don’t even have to draw anything.
There’s probably more elegant approaches, ones that replace the chars as you’re typing, etc. But this works for me :)

Joe

One Response to “Quick and Easy Password Field”

  1. admin Says:

    anybody have that code apple uses for password fields by any chance?

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word