How to show Xbutton button (clear button), which is always displayed in uisearchbar

In my application, I add a UISearchBar .

My intention is to enable the UISearch "X Button" panel (remove the uitextfield button) so that it is always visible.

I tried using the following code below to try to make the "X Button" always visible. However, this does not work. If I set tf.clearButtonMode = UITextFieldViewModeNever , the clear button in uitextfield is not displayed. I'm not sure what's wrong?

I really appreciate if anyone helps here. Why is this not working?

Code (not working)

 for (UIView* v in searchBar.subviews) { if ( [v isKindOfClass: [UITextField class]] ) { UITextField *tf = (UITextField *)v; tf.delegate = self; tf.clearButtonMode = UITextFieldViewModeAlways; break; } } 

Goal:

I want to always show the clear button if the length of the text is 0

  • i.e. if I do not enter any text.
+5
ios iphone ios5 uibutton
Aug 13 '13 at 11:28
source share
5 answers

You need to create a custom UIButton to clear the button

 UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom]; [clearButton setImage:img forState:UIControlStateNormal]; [clearButton setFrame:frame]; [clearButton addTarget:self action:@selector(clearTextField:) forControlEvents:UIControlEventTouchUpInside]; textField.rightViewMode = UITextFieldViewModeAlways; //can be changed to UITextFieldViewModeNever, UITextFieldViewModeWhileEditing, UITextFieldViewModeUnlessEditing [textField setRightView:clearButton]; 
+5
Aug 13 '13 at 11:46 on
source share
 UITextField *searchBarTextField = nil; for (UIView *subview in self.searchBar.subviews) { if ([subview isKindOfClass:[UITextField class]]) { searchBarTextField = (UITextField *)subview; searchBarTextField.clearButtonMode = UITextFieldViewModeAlways; break; } } 
+3
Aug 13 '13 at 11:46 on
source share

This is the default behavior in the search bar. Because if the UITextField empty, there is no need to click it.

+3
Aug 13 '13 at 11:51 on
source share

U can do it in Xib. I am attaching a screenshot.

enter image description here

And programmatically

 myUITextField.clearButtonMode = UITextFieldViewModeAlways; 
0
Aug 13 '13 at 11:45 on
source share

I tried to get it, but unfortunately, There is no way to configure using ClearButton (X) UITextField.

There is a way that if you only need this to resign KeyBoard, then simply overriding this method:

Just clear the field yourself and call resignFirstResponder.

 -(BOOL)textFieldShouldClear:(UITextField *)textField { textField.text = @""; [textField resignFirstResponder]; return NO; } 

The documentation for this is HERE

0
Aug 13 '13 at 12:12
source share



All Articles