UITextField has trailing whitespace after secureTextEntry toggle

后端 未结 18 1219
逝去的感伤
逝去的感伤 2020-12-29 19:27

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

相关标签:
18条回答
  • 2020-12-29 20:15

    I'm using this, Works fine.

    [self.yourTextField becomeFirstResponder];
    
    0 讨论(0)
  • 2020-12-29 20:16

    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!

    0 讨论(0)
  • 2020-12-29 20:17

    Swift 4

    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)
    }
    
    0 讨论(0)
  • 2020-12-29 20:18

    This is another possibility to solve this issue, where self.passwordText is the UITextField:

    if (self.passwordText.isFirstResponder) {
        [self.passwordText resignFirstResponder];
        [self.passwordText becomeFirstResponder];
    }
    
    0 讨论(0)
  • 2020-12-29 20:19

    You can fix it like this:

    NSString *currentText = self.textfield.text;
    self.textfield.text = @"";
    self.textfield.text = currentText;
    
    0 讨论(0)
  • 2020-12-29 20:19
    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

    0 讨论(0)
提交回复
热议问题