當我們向uisearchbar
添加一些文本時,我們在它的右側看到一個十字。當我們點擊這個時,uisearchbar
中的文本被清除。這是一個顯示十字的image。添加一個SearchBar方法
我需要做的是,我需要知道如何響應這個交叉事件(點擊時)。
當用戶點擊這個十字架,我需要打印NSLog(@"Cross clicked");
我怎麼能做到這一點編程?
當我們向uisearchbar
添加一些文本時,我們在它的右側看到一個十字。當我們點擊這個時,uisearchbar
中的文本被清除。這是一個顯示十字的image。添加一個SearchBar方法
我需要做的是,我需要知道如何響應這個交叉事件(點擊時)。
當用戶點擊這個十字架,我需要打印NSLog(@"Cross clicked");
我怎麼能做到這一點編程?
嘗試尋找的UISearchBarDelegate
文檔中:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText // called when text changes (including clear)
使用UISearchbarDelegate協議在UIViewController。有一種方法會被調用。
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
我想在用戶點擊uisearchBar上的X關閉按鈕時拍攝一個事件。 textDidChange不是該方法。 – Illep 2012-02-01 16:28:53
,如果你想要做不同的動作與清晰的按鈕..你可以建立一個自定義而不是默認,當點擊它實現的任何事件。
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];
如果您想在用戶點擊「X」按鈕通知,實施,以前的用戶建議的協議,並添加此實現:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if ([searchText isEqualToString:@""]) {
NSLog(@"%@", @"clear button pressed");
}
}
唯一的缺點,這是如果用戶退格到空白搜索字段,也會調用它。您需要找到一些方法來確定退格是否是最近的按鍵,可能通過檢查最後UITouch
的位置與退格鍵的已知位置進行比較。
您正在檢查'[searchText isEqualToString:@「」]',但是'searchText'是用戶在文本框中輸入的內容。這不是一個'X'按鈕,如 – Illep 2012-02-13 01:09:13
這個問題中的圖片所示,不過,無論何時點擊'x'按鈕,它都會清除文本並觸發'textDidChange'方法。這不是一個理想的解決方案,它更像是一種解決方法 – superhawk610 2012-02-13 03:45:17
我想在用戶點擊uisearchBar上的「X」關閉按鈕時拍攝一個事件。 'textDidChange'不是方法。 – Illep 2012-02-01 16:05:36