【问题标题】:UISearchBar scope buttons in UINavigationBar/UINavigationItemUINavigationBar/UINavigationItem 中的 UISearchBar 范围按钮
【发布时间】:2018-06-16 19:53:21
【问题描述】:

我正在尝试将 UISearchBar 添加到我的 UINavigationItem 但范围栏显示在搜索栏后面。有什么办法可以解决这个问题吗?

iOS:11.2 xCode:9.2

我的代码:

- (void)viewDidLoad 
{
    [super viewDidLoad];

    self.mySearchBar = [[UISearchBar alloc] init];
    self.mySearchBar.delegate = self;
    self.mySearchBar.scopeButtonTitles = @[@"item 1", @"item 2", @"item 3"];
    self.navigationItem.titleView = self.mySearchBar;
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self.mySearchBar setShowsScopeBar: TRUE];
    [self.mySearchBar setShowsCancelButton:TRUE animated:TRUE]; 
    return TRUE;
}   

结果:

【问题讨论】:

    标签: ios objective-c xcode uisearchbar uinavigationitem


    【解决方案1】:

    上下文

    问题在于UINavigationBar 提供了一种非常具体和熟悉的 iOS 风格,Apple 希望在应用程序中保持相同。默认导航栏不会扩展以适应其内容。

    当您设置导航项的titleView 时,您应该根据导航栏的大小来布局该视图中的内容,而不是相反。

    解决方案

    有几种可能的解决方案:

    1. Change the behaviorUINavigationBar 实例(不推荐)。
    2. UISearchBar 作为常规子视图放在导航栏下方。
    3. 使用UISearchController

    第一个选项绝对不应该是您的第一个解决方案,因为它需要您解决许多棘手的问题。作为最后的手段使用。

    选项 2 需要进行以下代码更改。将self.navigationItem.titleView = self.mySearchBar 替换为:

    [self.view addSubview:self.mySearchBar];
    UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
    [self.mySearchBar.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
    [self.mySearchBar.rightAnchor constraintEqualToAnchor:guide.rightAnchor].active = YES;
    [self.mySearchBar.leftAnchor constraintEqualToAnchor:guide.leftAnchor].active = YES;
    

    您还缺少在显示范围栏后调整UISearchBar 大小的代码。视图不会自行调整大小。因此,在您的 searchBarShouldBeginEditing: 方法中,在返回之前添加这一行:[self.mySearchBar sizeToFit];

    根据您的用例,第三种解决方案可能对您来说更容易。也就是说,使用UISearchController,其中包括锚定在屏幕顶部的自己的UISearchBar。它看起来就像上面的解决方案#2,如下图所示:

    Here is a great tutorial 如果您有兴趣,请使用UISearchController

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多