Search a UISearchBar with no text in Xcode5 / iOS7

浪尽此生 提交于 2019-12-06 06:30:25

问题


I'm updating my app for iOS 7 and one of my functions that allowed a search bar search button to be activated with no text in the search bar stopped working. I used the following code. ANy suggestions on how to make it work again? Thanks in advance.

UITextField *searchBarTextField = nil;
for (UIView *subview in self.searchBar.subviews)
{
    if ([subview isKindOfClass:[UITextField class]])
    {
        searchBarTextField = (UITextField *)subview;
        break;
    }
}
searchBarTextField.enablesReturnKeyAutomatically = NO;

回答1:


In iOS 7 there is a small change, now you have to iterated two levels.

  for (UIView *subView in self.searchBar.subviews){
    for (UIView *secondLeveSubView in subView.subviews){
    if ([secondLeveSubView isKindOfClass:[UITextField class]])
        {
            searchBarTextField = (UITextField *)2ndLeveSubView;
            break;
        }
    }
   }



回答2:


There is directly the option enablesReturnKeyAutomatically on search bar.

searchbar.enablesReturnKeyAutomatically = NO;



回答3:


Here is a solution using Swift. Just paste it in your viewDidLoad function and make sure that you have an IBOutlet of your searchBar in the code. (on my example below, the inputSearchBar variable is the IBOutlet)

   // making the search button available when the search text is empty
    var searchBarTextField : UITextField!
    for view1 in inputSearchBar.subviews {
        for view2 in view1.subviews {
            if view2.isKindOfClass(UITextField) {
                searchBarTextField = view2 as UITextField
                searchBarTextField.enablesReturnKeyAutomatically = false
                break
            }
        }
    }


来源:https://stackoverflow.com/questions/18971988/search-a-uisearchbar-with-no-text-in-xcode5-ios7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!