我试过了:
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];
但它效果不好...... 它显示自定义按钮,但是当你输入一些东西时,旧的东西会回来......
我该怎么做?
答案 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)