【问题标题】:resign keyboard when losing focus on uisearchbar失去对uisearchbar的关注时退出键盘
【发布时间】:2011-11-20 21:19:24
【问题描述】:

我正在我的应用程序的导航栏中创建一个 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 时退出搜索栏,但到目前为止还没有成功。

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

有人知道我可以做些什么来解决这个问题吗?

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

【问题讨论】:

    标签: objective-c cocoa-touch uisearchbar uisearchbardelegate


    【解决方案1】:

    解决了!

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

    我首先关闭了我的 2 个子视图上的 userInteraction,此时我开始使用 searchBar。

    - (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 中退出键盘,即使它挤满了大量的子视图。

    【讨论】:

      【解决方案2】:

      你试过了吗,

      UISearchBar *searchBar;
      

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

      并调用 any 方法

      [searchBar resignFirstResponder];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-06
        • 1970-01-01
        • 2017-11-10
        • 1970-01-01
        • 1970-01-01
        • 2020-03-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多