使用UISearchController以编程方式定位UISearchBar

Joe*_*oey 1 objective-c ios 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;
Run Code Online (Sandbox Code Playgroud)

目前我正在使用正确添加到我的UITableView标头的那个,但问题是它滚动表不是我想要的表.我想把它放在我的tableview之上,所以它反而尝试了但现在似乎已经消失了,除非我没有使用正确的值?

 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;
Run Code Online (Sandbox Code Playgroud)

Kho*_* Vo 5

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

self.searchController.searchBar.frame = CGRectMake(0, 64, self.searchController.searchBar.frame.size.width, 44.0);
Run Code Online (Sandbox Code Playgroud)

我有两个解决方案.我将向您展示简单的方法(您也可以使用storyboard):在ViewController中创建一个UIView,命名为searchBarView; 添加self.searchController.searchBarsearchBarView; 添加searchBarView到ViewController.

UIView *searchBarView = CGRectMake(0, 64, self.searchController.searchBar.frame.size.width, 44);
[searchBarView addSubView:self.searchController.searchBar];
[self.view addSubView:searchBarView];
Run Code Online (Sandbox Code Playgroud)

我假设您self.searchController.searchBar.sizeToFit()在viewDidload中设置了搜索控制器.如果它是通用应用程序,您需要添加此方法(至少在我的情况下,使一切工作):

- (void)viewDidLayoutSubviews {
    // you could check
    // if (IS_IPAD || (IS_IPHONE_6PLUS && UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))) 
    [self.searchController.searchBar sizeToFit];
}
Run Code Online (Sandbox Code Playgroud)

这是我在stackoverflow上的第一个答案.希望这有帮助^^.