在的UISearchBar文本字段的自定义按钮清晰(Custom clear button in U

2019-07-05 04:57发布

我试过了:

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];

但它并不能很好地工作......这显示自定义按钮,但是当你输入的东西,旧的得到的背...

我怎样才能做到这一点?

Answer 1:

如果你想在一个UISearchBar设置自定义清除按钮试试这个:

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

不要忘记设置的图像UIControlStateHighlighted

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


Answer 2:

您需要以下

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

强烈建议将这个顺序如果你想使用相同的图像串从UIControlStateHighlighted开始:图像1 =图像2 =图像。

在iOS7这是奇怪,但事实是UIControlStateNormal和UIControlStateHighlighted的直接命令不起作用。



Answer 3:

您可以隐藏你的取消按钮searchBarTextDidBeginEditing

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

而最令人惊奇,你也可以隐藏你通过清除按钮

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

按照我的回答敌人更多信息链接



Answer 4:

设置clearButtonModeUITextFieldViewModeNeverrightViewModeUITextFieldViewModeAlways



Answer 5:

在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)]


Answer 6:

Swift 4.2,4.1及以上版本的malex答案,

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

我也回答了这个在这里设置clear button tintColor沿results button定制。



文章来源: Custom clear button in UISearchBar text field