简体   繁体   中英

UITextField Clear Button with Placeholder bug?

I've got a UITextField with clearButton property set to "while editing". The textfield is right aligned. When i focus on the textfield to edit, the placeholder text doesn't move so the caret is flashing and half the placeholder text is wiped out.

Does anyone have a workaround?

I've just hit the exact same issue! It does look like a bug to me -- the area reserved for the clear button clips the placeholder to the right. The workaround I've found it to change the clear button style to "always", which is a misnomer as in fact the clear button still isn't displayed when the placeholder is visible (ie when the text is empty):

textField.clearButtonMode = UITextFieldViewModeAlways;

It does mean that the placeholder isn't aligned fully to the right (leaving space for the clear button, even though it's not there), which would be fine if the clear button was indeed displayed! This can be fixed by somehow ensuring the UITextField always contains a space instead of a blank, thus forcing the clear button to always (and that means always!) display.

I had the same problem and I solved managing the buttonMode (in my case I'm using a custom rightView) using the textfield delegate methods. In details I implemented these:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField.text.length == 0) {
        textField.rightViewMode = UITextFieldViewModeNever;
    } else {
        textField.rightViewMode = UITextFieldViewModeAlways;
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.text.length == 0) {
        textField.rightViewMode = UITextFieldViewModeNever;
    } else {
        textField.rightViewMode = UITextFieldViewModeAlways;
    }
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField.text.length == 0) {
        textField.rightViewMode = UITextFieldViewModeNever;
    } else {
        textField.rightViewMode = UITextFieldViewModeAlways;
    }
}

The textFieldDidChange: method is a custom action that I added to the UITextField for the UIControlEventEditingChanged control event.

我最终通过将前景色更改为银色/灰色来伪造占位符,并且当用户聚焦时,我清除了txt等。

此问题已在iOS 5中修复:)谢谢苹果!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM