7

我正在我的应用程序的导航栏中创建一个 UISearchBar 选项。我的应用由多个视图和子视图组成。我有这个主视图,其中对自己有 3 个其他观点。其中一个是空的(目前),另外两个上面有表格视图。

我希望我的键盘在我搜索时显示并在我进行实际搜索时或当我在 uisearchbar 外部触摸/单击时隐藏。我根据需要使用 searchbardelegate。

我可以通过以下方式使用 [searchBar resignFirstResponder] 隐藏键盘。

  • 当我按下返回键时。
  • 当我手动取消搜索时
  • 当我按下任何键盘按钮进行搜索或取消时。
  • 当我使用触摸屏幕的空白部分时

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {    
        UITouch *touch = [[event allTouches] anyObject];
        if ([mySearchBar isFirstResponder] && [touch view] != mySearchBar) {
            [mySearchBar resignFirstResponder];
        }
        [super touchesBegan:touches withEvent:event];
    }
    

我似乎无法做的是让它响应触摸我的 2 个表格视图之一。或者当我重新填充主视图以包含完全不同的东西时。

我尝试更改 touchesbegan 方法以在触摸 tableviews 时退出搜索栏,但到目前为止它还没有奏效。

我已经尝试了我亲爱的朋友先生发现的其他几件事。谷歌,但这一切似乎都是我需要的。

任何人都知道我可以做些什么来解决这个问题?

编辑:看起来,当使用断点时,touchesbegan-method 确实响应了背景视图,但是当我触摸表格视图或导航栏(包含 uisearchbar)时它没有响应。

4

2 回答 2

13

解决了!

- (BOOL) searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self.myViewController1.customView1 setUserInteractionEnabled:NO];
    [self.myViewController2.customView2 setUserInteractionEnabled:NO];   
    [searchBar setShowsCancelButton:YES animated:[mySettings animation]];
    return YES;   
}

在我开始使用 searchBar 的那一刻,我首先关闭了我的 2 个子视图上的 userInteraction。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{    
    UITouch *touch = [[event allTouches] anyObject];
    if ([self.mySearchBar isFirstResponder] && [touch view] != self.mySearchBar) 
    {
        [self.mySearchBar resignFirstResponder];
        [self.myViewController1.customView1 setUserInteractionEnabled:YES];
        [self.myViewController2.customView2 setUserInteractionEnabled:YES];
    }
    [super touchesBegan:touches withEvent:event];
}

然后,当我在 searchBar 之外单击/点击/触摸时,我首先退出仍然是第一响应者的键盘,并且在我为 2 个子视图重新设置 userInteraction 之后。这样做的顺序至关重要!

这段代码允许你在单个 mainViewController 中退出键盘,即使它挤满了大量的子视图。

于 2011-09-23T11:52:04.717 回答
0

你试过这个吗,

UISearchBar *searchBar;

接下来设置 的 Getter 和 Setter 属性UISearchBar

并调用 any 方法

[searchBar resignFirstResponder];
于 2013-09-04T13:28:03.783 回答