UISearchBar's scope button won't show up i

2019-08-30 03:53发布

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.

4条回答
Rolldiameter
2楼-- · 2019-08-30 04:21

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楼-- · 2019-08-30 04:34

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];
}
查看更多
Evening l夕情丶
4楼-- · 2019-08-30 04:41

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

查看更多
姐就是有狂的资本
5楼-- · 2019-08-30 04:42

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;
}
查看更多
登录 后发表回答