Custom clear button in UISearchBar text field

前端 未结 6 921
南笙
南笙 2020-12-06 19:12

I tried:

UITextField *searchtextfield = [searchBar.subviews objectAtIndex:1];
    UIButton *cButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cButt         


        
相关标签:
6条回答
  • 2020-12-06 19:42

    Set clearButtonMode to UITextFieldViewModeNever and rightViewMode to UITextFieldViewModeAlways

    0 讨论(0)
  • 2020-12-06 19:42

    In swift 2.2, following code worked for me

            [UISearchBar .appearance().setImage(UIImage(named: "search_clear_icon"), forSearchBarIcon: .Clear, state: .Normal)]
    
        [UISearchBar .appearance().setImage(UIImage(named: "search_clear_icon"), forSearchBarIcon: .Clear, state: .Highlighted)]
    
    0 讨论(0)
  • 2020-12-06 19:47

    You can hide your cancel button on searchBarTextDidBeginEditing

    - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
    {
        [searchBar setShowsCancelButton:NO animated:YES];
    }  
    

    And the most amazing you can also hide you clear button by

    UITextField *textField=(UITextField*)[[searchBar subviews]objectAtIndex:1];
    textField.clearButtonMode=UITextFieldViewModeNever; 
    

    Follow my answer foe more info link

    0 讨论(0)
  • 2020-12-06 19:54

    Swift 4.2, 4.1+ of malex answer,

    UISearchBar.appearance().setImage(UIImage(named: "image1"), for: .clear, state: .normal)
    UISearchBar.appearance().setImage(UIImage(named: "image2"), for: .clear, state: .highlighted)
    

    I also answered this here to set clear button tintColor along with results button customization.

    0 讨论(0)
  • 2020-12-06 19:56

    If you want to set a custom clear button in a UISearchBar try this:

    [[UISearchBar appearance] setImage:[UIImage imageNamed:@"MyClearButton.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
    

    Don't forget to set an image for UIControlStateHighlighted

    [[UISearchBar appearance] setImage:[UIImage imageNamed:@"HighlightedClearButton.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
    
    0 讨论(0)
  • 2020-12-06 20:01

    You need the following

    [searchBar setImage:[UIImage imageNamed:@"image1"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
    [searchBar setImage:[UIImage imageNamed:@"image2"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
    

    It is strongly recommended to place strings in this order starting from UIControlStateHighlighted in case you want to use the same image: image1=image2=image.

    In iOS7 it is weird but fact that direct order of UIControlStateNormal and UIControlStateHighlighted doesn't work.

    0 讨论(0)
提交回复
热议问题