Show "#" instead of "bullets" in UITextField for "Secure Text Entry"

Viewed 3231

I have a requirement to show "#" instead of bullets for password field. But as there is no default option available for it in UITextField.

I have tried to write custom logic in "shouldChangeCharactersInRange" But i am not able to handle the index when user will remove or add any specific character from in-between.

So here are my questions :- 1. Do i need to find any library 2. There is any other default option available for it? 3. Need to write custom logic for it? If so where i can handle it correctly "shouldChangeCharactersInRange" or "textFieldDidChange"

3 Answers

Improved Mr. Bean's answer in swift 5. To fix Copy&Paste bugs.

var passNSString : NSString = ""
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        var hashPassword = String()
        
        passNSString = passNSString.replacingCharacters(in: range, with: string) as NSString
        for _ in 0..<passNSString.length {  hashPassword += "#" }
        textField.text = hashPassword
        print("str", passNSString)
        return false
        
    }
Related