I have a button that toggles between Show/Hide mode (i.e. toggles a UITextField between secureTextEntry NO and YES). The purpose of which is to allow the user to see the pa
I'm using this, Works fine.
[self.yourTextField becomeFirstResponder];
To get the cursor to reposition correctly, setting the font attributes seemed to do the trick for me.
// Hack to update cursor position
self.passwordTf.defaultTextAttributes = @{NSFontAttributeName: textFieldFont, NSForegroundColorAttributeName: textFieldColor};
// Change secure entry
self.passwordTf.secureTextEntry = !self.passwordTf.secureTextEntry;
Tested on iOS8, iOS9. Hope it helps!
Bug is on radar, there is explanation of workaround also: http://www.openradar.me/38465011
Here is cut of temporary workaround how to natively update caret (cursor) position.
// update caret position
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
let (beginning, end) = (self.beginningOfDocument, self.endOfDocument)
self.selectedTextRange = self.textRange(from: beginning, to: end)
self.selectedTextRange = self.textRange(from: end, to: end)
}
This is another possibility to solve this issue, where self.passwordText is the UITextField:
if (self.passwordText.isFirstResponder) {
[self.passwordText resignFirstResponder];
[self.passwordText becomeFirstResponder];
}
You can fix it like this:
NSString *currentText = self.textfield.text;
self.textfield.text = @"";
self.textfield.text = currentText;
UITextPosition *beginning = [self.passwordField beginningOfDocument];
[self.passwordField setSelectedTextRange:[self.passwordField textRangeFromPosition:beginning
toPosition:beginning]];
UITextPosition *end = [self.passwordField endOfDocument];
[self.passwordField setSelectedTextRange:[self.passwordField textRangeFromPosition:end
toPosition:end]];
This is what I used for iOS 8