2012-02-01 73 views
0

當我們向uisearchbar添加一些文本時,我們在它的右側看到一個十字。當我們點擊這個時,uisearchbar中的文本被清除。這是一個顯示十字的image添加一個SearchBar方法

我需要做的是,我需要知道如何響應這個交叉事件(點擊時)。

當用戶點擊這個十字架,我需要打印NSLog(@"Cross clicked");

我怎麼能做到這一點編程?

回答

0

嘗試尋找的UISearchBarDelegate文檔中:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText // called when text changes (including clear) 
+0

我想在用戶點擊uisearchBar上的「X」關閉按鈕時拍攝一個事件。 'textDidChange'不是方法。 – Illep 2012-02-01 16:05:36

0

使用UISearchbarDelegate協議在UIViewController。有一種方法會被調用。

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 

http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UISearchBarDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UISearchBarDelegate

+0

我想在用戶點擊uisearchBar上的X關閉按鈕時拍攝一個事件。 textDidChange不是該方法。 – Illep 2012-02-01 16:28:53

0

,如果你想要做不同的動作與清晰的按鈕..你可以建立一個自定義而不是默認,當點擊它實現的任何事件。

UISearchBar *searchBar = yourSearchBar; 
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 newImageFromResource:@"yourButtonImage"] forState:UIControlStateNormal];//If you want like the x button put image similar to it. 
cButton.contentMode = UIViewContentModeScaleToFill; 
[cButton addTarget:self action:@selector(clearButtonPressed) forControlEvents:UIControlEventTouchUpInside];//This is the custom event 
[searchtextfield setRightView:cButton]; 
[searchtextfield setRightViewMode:UITextFieldViewModeAlways]; 
+0

如果您查看我在問題中鏈接的圖片,您會在搜索欄中看到一個用「X」表示的CLOSE按鈕。當用戶點擊它時,我需要打印一個NSLog。 – Illep 2012-02-01 17:11:58

+0

是的,我看到..這是按鈕被稱爲清除按鈕..其內置按鈕從iOS ..你不能通過它自定義事件,直到你用自定義按鈕替換它..如果你感興趣,我會告訴你如何。 – 2012-02-12 11:46:55

+0

是的,請你告訴我該怎麼做? – Illep 2012-02-12 11:53:48

0

如果您想在用戶點擊「X」按鈕通知,實施,以前的用戶建議的協議,並添加此實現:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { 
    if ([searchText isEqualToString:@""]) { 
     NSLog(@"%@", @"clear button pressed"); 
    } 
} 

唯一的缺點,這是如果用戶退格到空白搜索字段,也會調用它。您需要找到一些方法來確定退格是否是最近的按鍵,可能通過檢查最後UITouch的位置與退格鍵的已知位置進行比較。

+0

您正在檢查'[searchText isEqualToString:@「」]',但是'searchText'是用戶在文本框中輸入的內容。這不是一個'X'按鈕,如 – Illep 2012-02-13 01:09:13

+0

這個問題中的圖片所示,不過,無論何時點擊'x'按鈕,它都會清除文本並觸發'textDidChange'方法。這不是一個理想的解決方案,它更像是一種解決方法 – superhawk610 2012-02-13 03:45:17

相關問題