ios - 使用 UISearchController 以编程方式定位 UISearchBar

标签 ios objective-c uisearchcontroller

我试图将我的 UISearchBar 直接放在我的 UINavigationBar 下,但我遇到了它根本没有出现的问题。我正在使用 iOS8 的新 searchController。

 self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
 self.searchController.searchResultsUpdater = self;
 self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
 self.salesTableView.tableHeaderView = self.searchController.searchBar;

目前我正在使用它正确地将它添加到我的 UITableView 标题中,但问题是它与表格一起滚动,这不是我想要的。我希望它在我的桌面 View 上方,所以它会粘住并尝试了这个,但它现在似乎已经消失了,除非我没有使用正确的
值(value)观?
 self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
 self.searchController.searchResultsUpdater = self;
 self.searchController.searchBar.frame = CGRectMake(0, 0, self.searchController.searchBar.frame.size.width, 44.0);
 //  self.salesTableView.tableHeaderView = self.searchController.searchBar;

最佳答案

因为原点是(0,0),所以会被状态栏和导航栏隐藏。如果更改为:您应该会看到搜索栏:

self.searchController.searchBar.frame = CGRectMake(0, 64, self.searchController.searchBar.frame.size.width, 44.0);

我有两个解决方案。我将向您展示一种简单的方法(您也可以使用 Storyboard):在您的 ViewController 中创建一个 UIView,命名为 searchBarView ;添加 self.searchController.searchBar进入searchBarView ;添加 searchBarView到你的 ViewController。
UIView *searchBarView = CGRectMake(0, 64, self.searchController.searchBar.frame.size.width, 44);
[searchBarView addSubView:self.searchController.searchBar];
[self.view addSubView:searchBarView];

我假设您设置了搜索 Controller self.searchController.searchBar.sizeToFit()在 viewDidload.如果是通用应用程序,则需要添加此方法(至少在我的情况下使一切正常):
- (void)viewDidLayoutSubviews {
    // you could check
    // if (IS_IPAD || (IS_IPHONE_6PLUS && UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))) 
    [self.searchController.searchBar sizeToFit];
}

这是我在stackoverflow上的第一个答案。希望对您有所帮助^^。

关于ios - 使用 UISearchController 以编程方式定位 UISearchBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26639791/

相关文章:

iphone - 创建基本的内容浏览 iPhone 应用程序

swift - 如何将 UISearchController 放置到 navigationTitle 以及如何通过按钮启用和禁用它?

ios - Swift iOS - 如何让键盘在显示 SearchController 的同时显示自身?

ios - LineChart 绘图数据未填充其 UIView

ios - 企业iOS : will adding an existing bundle ID to an app group invalidate already deployed apps?

ios - iOS8中的通讯录授权

swift - UISearchController searchBar 不更新 barTintColor

ios - 乱序调用的 GCD 函数

iphone - 如何以编程方式在 Xcode 4x 中定位构建的产品(应用程序)

iphone - 如何获取字典数组中特定键的值?