How to show Xbutton(clear button) always visible i

2019-02-23 11:49发布

In my application, I am adding a UISearchBar.

My intent is to enable the UISearch Bar "X button"(clear button in UITextField) to be always visible.

I have tried using the following code below to try to make the "X Button" be always visible. However, it does not work. If I set tf.clearButtonMode = UITextFieldViewModeNever, the clear button in uitextfield not showing. I am not sure what is wrong?

I would really appreciate anyone's help 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 text length is equal to 0

  • i.e. if I don't input any text.

5条回答
叼着烟拽天下
2楼-- · 2019-02-23 12:19
UITextField *searchBarTextField = nil;
    for (UIView *subview in self.searchBar.subviews)
    {
        if ([subview isKindOfClass:[UITextField class]])
        {
            searchBarTextField = (UITextField *)subview;
            searchBarTextField.clearButtonMode = UITextFieldViewModeAlways;
            break;
        }
    }
查看更多
戒情不戒烟
3楼-- · 2019-02-23 12:22

This is the default behavior of the search bar. Because if the UITextField is blank then there is no need to press it.

查看更多
Fickle 薄情
4楼-- · 2019-02-23 12:31

I tried to get it but unfortunately , There is no Way of Customising with the ClearButton(X) of UITextField .

There is a way that If You only need it to get resign the KeyBoard , Then just overriding this method :

Just clear the field yourself and call resignFirstResponder .

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

    return NO;
}

Documentation about it HERE

查看更多
beautiful°
5楼-- · 2019-02-23 12:40

You have to need create a Custom UIButton for clear 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];
查看更多
再贱就再见
6楼-- · 2019-02-23 12:41

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

enter image description here

And programmatically

myUITextField.clearButtonMode = UITextFieldViewModeAlways;
查看更多
登录 后发表回答