Hide UISearchBar clear text button

前端 未结 15 1594
时光说笑
时光说笑 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 05:51

    Swift 3 solution :

    extension UISearchBar{
        var textField : UITextField{
            return self.value(forKey: "_searchField") as! UITextField
        }
    }
    

    Usage :

    searchBar.textField.clearButtonMode = .never
    
    0 讨论(0)
  • 2020-12-31 05:53

    thijsonline's answer in swift:

    (UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])).clearButtonMode = .never
    
    0 讨论(0)
  • 2020-12-31 05:54

    Swift 5

    Tested on iOS 13

    One liner working for me:

    searchBar.searchTextField.clearButtonMode = .never
    

    You can also set it to .whileEditing to have it displayed when the user is typing and then removed when the search bar loses focus.

    0 讨论(0)
  • 2020-12-31 05:58

    Swift 4

    Adding to Alexander's answer and block user interaction on clear button:

    To hide button:

    searchBar.setImage(UIImage(), for: .clear, state: .normal)
    

    To disable user interaction on the clear button, simply subclass UISearchBar

    class CustomSearchBar: UISearchBar {
    
        override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
            let view = super.hitTest(point, with: event)
            if view is UIButton {
                return view?.superview // this will pass-through all touches that would've been sent to the button
            }
            return view
        }
    }
    
    0 讨论(0)
  • 2020-12-31 05:58

    Try this:

    - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
        UITextField *textField = [searchBar valueForKey:@"_searchField"];
        textField.clearButtonMode = UITextFieldViewModeNever;
    
    }
    
    0 讨论(0)
  • 2020-12-31 05:59

    In Case of Swift 2.3 just use :

    var searchBar = UISearchBar();
    searchBar.frame = CGRectMake(0, 0, 00, 20))
    for subview: UIView in (searchBar.subviews.first?.subviews)!
            {
                if (subview.isKindOfClass(UITextField) )
                {
                    let textFieldObject = (subview as! UITextField)
                    textFieldObject.clearButtonMode = .Never;
                }
            }
    
    0 讨论(0)
提交回复
热议问题