UISearchBar's scope button won't show up i

2019-08-30 04:13发布

问题:

I know this question was asked several times before, and it was solved(Before I was using that solution with iOS4 and 5). My recent project involves using UISearchBar with some other views, and I want to show it's scope buttons when it becomes active. Before, in UISearchBardelegate's - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar I was doing

[searchBar setShowsScopeBar:YES];
[searchBar sizeToFit];

and it was showing scope buttons. But now, on iOS6 this code does nothing. UISearchBar is added in IB, it's delegate is set to my view controller. Anybody has solution for this problem? Thanks in advance.

回答1:

It looks like what's going on is that the UISearchBar is failing to invalidate its intrinsic content size when it shows and hides the scope bar.

Until it's fixed in UIKit, it's extremely easy to work around it by simply subclassing UISearchBar and overriding a single method:

- (void)setShowsScopeBar:(BOOL)showsScopeBar {
  if ([self showsScopeBar] != showsScopeBar) {
    [self invalidateIntrinsicContentSize];
  }
  [super setShowsScopeBar:showsScopeBar];
}


回答2:

I reported this as a bug to Apple and got an answer how to fix it:

Just subclass UISearchBar and override -setShowsScopeBar:

- (void)setShowsScopeBar:(BOOL)showsScopeBar
{
    if (self.showsScopeBar != !!showsScopeBar) [self invalidateIntrinsicContentSize];
    [super setShowsScopeBar:showsScopeBar];
}

UPDATE: This is fixed in iOS 7.



回答3:

Ok, problem was with iOS 6 auto layout thing, once I'va removed it, problem was gone. Thanks everyone :)



回答4:

Another way to do this in iOS 6.0 without having to subclass UISearchBar is just by adjusting the frame size in the Search Bar Delegate:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    NSMutableArray *ma = [NSMutableArray arrayWithCapacity:2];

    [ma addObject:@"One"];
    [ma addObject:@"Two"];

    CGRect f = searchBar.frame;
    f.size.height += 44.0f;
    searchBar.frame = f;

    searchBar.scopeButtonTitles = [ma copy];
    searchBar.showsScopeBar = YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    CGRect f = searchBar.frame;
    f.size.height -= 44.0f;
    _searchBar.frame = f;

    searchBar.scopeButtonTitles = nil;
    searchBar.showsScopeBar = NO;
}