Hide UISearchBar clear text button

前端 未结 15 1607
时光说笑
时光说笑 2020-12-31 05:31

I would like to know how to hide or not display the UISearchBar cross that appears in the textField fo the UISearchBar

I have

相关标签:
15条回答
  • 2020-12-31 06:01

    Swift 3, based on @Alexsander answer:

    searchBar.setImage(UIImage(), for: .clear, state: .normal)
    
    0 讨论(0)
  • 2020-12-31 06:02

    You need to get the textField of the Search Bar:

    UITextField *textField = [searchBar valueForKey:@"_searchField"];
    textField.clearButtonMode = UITextFieldViewModeNever;
    

    hope this help! =)

    0 讨论(0)
  • 2020-12-31 06:04

    Based on @Gines answer, here is the Swift version:

    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        guard let firstSubview = searchBar.subviews.first else { return }
    
        firstSubview.subviews.forEach {
            ($0 as? UITextField)?.clearButtonMode = .never
        }
    }
    
    0 讨论(0)
  • 2020-12-31 06:05

    There's a better way to do this, and you don't have to use private APIs or traverse subviews to do it, so this solution is App Store safe.

    UISearchBar has a built-in API for doing this:

    [UISearchBar setImage:forSearchBarIcon:state]

    The SearchBar icon key you want is UISearchBarIconClear, and you want the UIControlStateNormal state. Then give it a clear image for the image, and you're done.

    So, it should look like this:

    [searchBar setImage:clearImage forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
    
    0 讨论(0)
  • 2020-12-31 06:05

    I tried different solutions about this issue, even the one selected in this post, but they didn't work.

    This is the way I found to solve this issue:

    UIView *subview = [[searchBar subviews] firstObject]; //SearchBar only have one subview (UIView)
    
    //There are three sub subviews (UISearchBarBackground, UINavigationButton, UISearchBarTextField)
    for (UIView *subsubview in subview.subviews)
    {
        //The UISearchBarTextField class is a UITextField. We can't use UISearchBarTextField directly here.
        if ([subsubview isKindOfClass: [UITextField class]])
        {
                [(UITextField *)subsubview setClearButtonMode:UITextFieldViewModeNever];
        }
    }
    
    0 讨论(0)
  • 2020-12-31 06:09

    Swift 2.3, based on @Alexsander answer:

    searchBar.setImage(UIImage(named: "SearchClearIcon"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Highlighted)
    searchBar.setImage(UIImage(named: "SearchClearIcon"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Normal)
    
    0 讨论(0)
提交回复
热议问题