2012-12-13 34 views
4

自定義清除按鈕我想:中的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]; 

但它並不能很好地工作...... 它會顯示自定義按鈕,但是當你輸入的東西,老一所送的回.. 。

我該怎麼做?

+0

跟隨我的回答http://stackoverflow.com/questions/13799074/how-to-override-the-cancel-button-in-the- uisearchbar/13799144#13799144 – Rajneesh071

+0

是你的問題解決了嗎? – Rajneesh071

回答

0

可以隱藏取消searchBarTextDidBeginEditing

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

而且最神奇的按鈕,您也可以隱藏你清除按鈕通過

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

按照我的回答敵人更多信息link

+0

我認爲這是關於清除按鈕不取消按鈕。 – Mert

+0

沒有它的取消按鈕@Mert,它已經從函數名稱清除setShows「取消」按鈕 – Rajneesh071

+0

是的,你的答案是取消按鈕,但@ 1337code已問清除按鈕。 – Mert

0

套裝clearButtonModeUITextFieldViewModeNeverrightViewModeUITextFieldViewModeAlways

7

如果你想設置一個UISearchBar自定義清除按鈕試試這個:

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

不要忘記設置的圖像UIControlStateHighlighted

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

這個解決方案在iOS 7.1上完美。 – Alex

+0

謝謝,完美的作品。如果有人正在尋找這個代碼的Swift版本,可以在這裏找到它:http://stackoverflow.com/a/25419881/1447641 – Apfelsaft

+0

它爲我工作。謝謝。我以爲我必須用UISearchBar對象實例來完成它。 –

5

您需要以下

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

強烈建議您按此順序放置字符串,從UIControlStateHighlighted 如果您想使用相同的圖像:image1 = image2 =圖像。

在iOS7中很奇怪,但實際上UIControlStateNormal和UIControlStateHighlighted的直接順序不起作用。

0

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