Archive for June, 2008

Quick and Easy iPhone SDK Password Field

You don’t even need to subclass UITextField 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

Comments