2012-02-01 76 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

相关问题