UITextField Clear Button with Placeholder bug?
I've got a UITextField with clearButton property set to "w开发者_Python百科hile 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 (i.e. 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.
I ended up faking the placeholder by changing the foreground color to silver/gray and when user focuses, i clear out that txt, etc.
This issue has been fixed in iOS 5 :) Thank you, Apple!
精彩评论