UISearchBar文本字段中的自定义清除按钮

时间:2012-12-13 14:34:09

标签: iphone ios ipad uitextfield uisearchbar

我试过了:

UITextField *searchtextfield = [searchBar.subviews objectAtIndex:1];
    UIButton *cButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cButton.frame = CGRectMake(0, 0, 20 , 20);
    cButton.backgroundColor = [UIColor clearColor];
    [cButton setImage:[UIImage imageNamed:@"x-button"] forState:UIControlStateNormal];//your button image.
    cButton.contentMode = UIViewContentModeScaleToFill;
    [cButton addTarget:self action:@selector(xButtonPressed) forControlEvents:UIControlEventTouchUpInside];//This is the custom event
    [searchtextfield setRightView:cButton];
    [searchtextfield setRightViewMode:UITextFieldViewModeWhileEditing];

但它效果不好...... 它显示自定义按钮,但是当你输入一些东西时,旧的东西会回来......

我该怎么做?

6 个答案:

答案 0 :(得分:8)

如果要在UISearchBar中设置自定义清除按钮,请尝试:

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

不要忘记为UIControlStateHighlighted

设置图片
[[UISearchBar appearance] setImage:[UIImage imageNamed:@"HighlightedClearButton.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];

答案 1 :(得分:6)

您需要以下

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

强烈建议从 UIControlStateHighlighted 开始按此顺序放置字符串 如果你想使用相同的图像:image1 = image2 = image。

在iOS7中,它很奇怪,但事实是UIControlStateNormal和UIControlStateHighlighted的直接顺序不起作用。

答案 2 :(得分:0)

您可以在searchBarTextDidBeginEditing

上隐藏取消按钮
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:NO animated:YES];
}  

最令人惊讶的是你也可以通过

隐藏你的按钮
UITextField *textField=(UITextField*)[[searchBar subviews]objectAtIndex:1];
textField.clearButtonMode=UITextFieldViewModeNever; 

按照我的回答更多信息link

答案 3 :(得分:0)

clearButtonMode设为UITextFieldViewModeNever,将rightViewMode设为UITextFieldViewModeAlways

答案 4 :(得分:0)

在swift 2.2中,以下代码为我工作

        [UISearchBar .appearance().setImage(UIImage(named: "search_clear_icon"), forSearchBarIcon: .Clear, state: .Normal)]

    [UISearchBar .appearance().setImage(UIImage(named: "search_clear_icon"), forSearchBarIcon: .Clear, state: .Highlighted)]

答案 5 :(得分:0)

Swift,共malex个答案的 4.2,4.1 +

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

我还回答了here,将clear button tintColor设置为results button自定义。