4

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;
Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
user1681673
  • 368
  • 1
  • 6
  • 28

3 Answers3

5

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

  for (UIView *subView in self.searchBar.subviews){
    for (UIView *secondLeveSubView in subView.subviews){
    if ([secondLeveSubView isKindOfClass:[UITextField class]])
        {
            searchBarTextField = (UITextField *)2ndLeveSubView;
            break;
        }
    }
   }
Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Adnan Aftab
  • 14,377
  • 4
  • 45
  • 54
5

There is directly the option enablesReturnKeyAutomatically on search bar.

searchbar.enablesReturnKeyAutomatically = NO;
CarmenA
  • 404
  • 12
  • 22
1

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
            }
        }
    }
rsc
  • 10,348
  • 5
  • 39
  • 36
  • Thank you for this @RSC. I wondered what was "searchBarTextField". I think you may have forgotten to declare it: `let searchBarTextField = view2 as UITextField` Thank you anyway, this was the answer I was looking for. – Quentin Malgaud Oct 27 '15 at 17:18
  • Quentin, I declared it in the first code line: var searchBarTextField : UITextField! – rsc Oct 27 '15 at 20:54