问题
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