搜索栏取消按钮不起作用

Ram*_*amz 6 iphone cocoa-touch objective-c uisearchbar

我的应用程序有一个搜索栏,用于从表视图中搜索记录,该视图由sqlite DB填充.我的问题是,当视图打开时,"取消"按钮未启用,我也无法触及,就像只有图像一样.它就在那里,但没有动作.当我们点击该搜索栏文本时,取消按钮将更改为"已完成",它将启用一个.所以这是我的代码

这是我的搜索栏视图,看到取消按钮.它没有启用

这是我的搜索栏view.see取消按钮.它没有启用

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


    newSearchBar.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;

    NSLog(@"search begin edit") ;

    //searchString = searchBar.text;

    //NSLog(@"print did edit searchstring : %@", searchString) ;

    for(UIView *view in [searchBar subviews])       
    {

        //shareItemId =newSearchBar.text;

        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            [(UIBarItem *)view setTitle:@"Done"];

        }
        }

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    NSLog(@"searchBarTextDidEndEditing:");


    [searchBar resignFirstResponder];
    //[self dismissModalViewControllerAnimated:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"searchBarSearchButtonClicked");


    searchString = searchBar.text;
    NSLog(@"search %@", searchBar.text);
    [newSearchBar setShowsCancelButton:NO animated:YES];

    [searchBar resignFirstResponder];
    //[self dismissModalViewControllerAnimated:YES];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar

{  
    NSLog(@" searchBarCancelButtonClicked");


    [searchBar resignFirstResponder];

     shareItemName =newSearchBar.text;

    [self dismissModalViewControllerAnimated:YES];

}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {

    NSLog(@"searchBarShouldBeginEditing");


    [newSearchBar setShowsCancelButton:YES animated:YES];
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

这些是我的代表

请检查我的代码并给我答案.我需要在加载视图时启用"取消"按钮,它的操作将返回到上一个视图

我需要这样的

在此输入图像描述

或者我怎么能在令人兴奋的取消按钮上添加另一个取消按钮.所以我可以启用它.请给我所有细节

Ray*_*eck 6

您需要将UISearchDisplayController设置为ACTIVE,如下所示:

 [mySearchDisplayController setActive:YES animated:YES];
Run Code Online (Sandbox Code Playgroud)

或更简单地说:

 mySearchDisplayController.active = YES;
Run Code Online (Sandbox Code Playgroud)


Avi*_*ron 4

我的猜测是,Apple 制作 UISearchBar 的方式是,如果搜索文本字段为空或不是第一响应者,则取消按钮将被禁用。

这是有道理的,因为除了实际取消搜索之外,您不应该将“取消”按钮用于其他目的。并且由于没有要取消的搜索 - 该按钮被禁用。

如果您仍然希望该按钮在视图呈现时立即处于活动状态,您可以viewWillAppear:调用[mySearchBar becomeFirstResponder];

这将导致键盘出现并且按钮将被启用。然后,如果用户点击取消,您可以拦截它以返回到上一个视图。(我不确定苹果是否会喜欢这种行为)。

示例代码:

-(void) viewWillAppear : (BOOL) animated
{
    [super viewWillAppear:animated];
    // Make keyboard pop and enable the "Cancel" button.
    [self.mySearchBar becomeFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)