Search code examples
iosswiftuitextfield

UITextField secureTextEntry toggle set incorrect font


I have an UITextField which I use as a password field. It has by default secureTextEntry set to true. I also have a UIButton to toggle the show/hide of the password.

When I change the textfield from secureTextEntry set to true to false, the font gets weird. Seems it becomes Times New Roman or similar.

I have tried re-setting the font to system with size 14, but it didn't change anything.

Example of what happens (with initial secureTextEntry set to true): Example

My code:

@IBAction func showHidePwd(sender: AnyObject) {
    textfieldPassword.secureTextEntry = !textfieldPassword.secureTextEntry

    // Workaround for dot+whitespace problem
    if !textfieldPassword.secureTextEntry {
        let tempString = textfieldPassword.text
        textfieldPassword.text = nil
        textfieldPassword.text = tempString
    }
    textfieldPassword.font = UIFont.systemFontOfSize(14)

    if textfieldPassword.secureTextEntry {
        showHideButton.setImage(UIImage(named: "EyeClosed"), forState: .Normal)
    } else {
        showHideButton.setImage(UIImage(named: "EyeOpen"), forState: .Normal)
    }

    textfieldPassword.becomeFirstResponder()
}

Solution

  • Changing the font of UITextField will not take effect until you first set the font to nil. Try following.

    textfieldPassword.font = nil
    textfieldPassword.font = UIFont.systemFontOfSize(14.0)