Search code examples
iosuitextfieldnsrange

iOS - Replace text with another form of text


I'm creating a login page for users, and I have a UITextField for users to input a password. I also have a summary page at the end, which gives back the users information including the password. I'm trying to change the password to display as "secure" or with stars instead of the text. For example:

passInput.text = @"password"
changed to: ********;

I am using the following code to accomplish the task:

NSString *password = passInput.text;
NSRange range = NSMakeRange(0,passInput.text.length);
NSString *formattedPassword = [password stringByReplacingCharactersInRange:range withString:@"*"];
[sumPassword setText:newPassText];

The problem is that it returns only one star and not 8 stars as I would think it should.

What am I missing?


Solution

  • You could just set:

    passInput.secureTextEntry = YES;
    

    so that it shows dots instead of letters when writing in that field.

    Otherwise you could make it like:

    NSUInteger length = passInput.text.length;
    NSMutableString * str = [[NSMutableString alloc] init];
    
    for (NSUInteger i = 0 ; i < length ; ++i) {
        [str appendString:@"*"];
    }
    

    or...

    NSUInteger length = passInput.text.length;
    // Make this long enough
    NSString * str = @"*********************************************************";
    NSString * pass = [str substringToIndex:length];