Awesome.Apple Awesome.Apple - 5 months ago 19
Swift Question

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

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"

Answer Source
  1. No you dont need to find any 3rd party library for this logic
  2. No there is no default option available for your need
  3. Yes, you need to write a custom logic for your demand, So here it goes...

    var passwordText = String()
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    if textField == textFieldPassword {
    
        var hashPassword = String()
        let newChar = string.characters.first
        let offsetToUpdate = passwordText.index(passwordText.startIndex, offsetBy: range.location)
    
        if string == "" {
            passwordText.remove(at: offsetToUpdate)
            return true
        }
        else { passwordText.insert(newChar!, at: offsetToUpdate) }
    
        for _ in passwordText.characters {  hashPassword += "#" }
        textField.text = hashPassword
        return false
    }