Pramod More
Pramod More

Reputation: 1250

iOS textfield cursor position wrong

While toggling iOS textField isSecureTenxtEntry.

enter image description here

My code is like this

textField?.isSecureTextEntry = !textField.isSecureTextEntry

Device is iPhone 6.

Upvotes: 1

Views: 1774

Answers (2)

Ankit Jayaswal
Ankit Jayaswal

Reputation: 5679

This problem raised due to the different character size of the secure dot character and simple character. Dot character are wider in size that's why when you disable secure text entry, character contracts but cursor stays at the same position.

Although this issue should not be in the latest Xcode but I had a same problem in Xcode 6.3.

Explanation:

When you click button to toggle the secureTextEntry, set the becomeFirstResponder again for your textField, it will invoke the keyboard observer and reset the cursor to right position.

    textField?.isSecureTextEntry = !textField.isSecureTextEntry

    if textField?.isFirstResponder {
        textField?.becomeFirstResponder()
    }

Hope this will help you.

Upvotes: 6

Indrajeet
Indrajeet

Reputation: 5666

First discuss why this is happening.

Dot character width is different from normal character, so when you change value of isSecureTextEntry property, UITextField is not refreshing thats why the extra space appears.

To solve this problem, you can use below code

txtPassword.isSecureTextEntry = !txtPassword.isSecureTextEntry
let str = txtPassword.text
txtPassword.text = ""
txtPassword.text = str

What I do in above code, after changing value of isSecureTextEntry store value in temporary variable and empty the UITextField and after that reassign the same UITextField by using temporary variable.

Upvotes: 7

Related Questions