UITextField has trailing whitespace after secureTextEntry toggle

后端 未结 18 1422
逝去的感伤
逝去的感伤 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:28

    PRE-iOS-8.0 (dated solution)... In your button's action method (toggling between secureTextEntry YES and NO), simply set UITextField's text property to its current text value. Although this may seem redundant and a bit like a hack, this will redraw the cursor in the right position. Here's an example of what your button's action method should look like now...

    -(void)toggleButtonPressed:(UIButton*)sender
    {
        // Toggle between secure and not-so-secure entry
        self.toggleButton.selected = !self.toggleButton.selected;
        self.textfield.secureTextEntry = !self.toggleButton.selected;
    
        // * Redundant (but necessary) line *
        [self.textfield setText:self.textfield.text];
    }
    

    POST-iOS-8.0... As of iOS 8.0, it appears that UITextField's text setter no longer redraws the cursor when called with a string equal to its current string value. Now, we need to take this a step further and actually change the text value before resetting it again. Replace the above setText: line with something like these lines.

    // * Extra redundant (but necessary) lines *
    NSString *currentText = self.textfield.text;
    [self.textfield setText:@"Arbitrary string..."]; // Change the value
    [self.textfield setText:currentText]; // Reset the value
    

提交回复
热议问题