具体来说,对于iOS 11(而不是之前的操作系统),当您点击搜索栏开始输入时,它会跳转到屏幕顶部。
我可以使用以下代码在搜索栏已经靠近屏幕顶部时解决此问题:
if #available(iOS 11, *) {
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
} else {
BugsTable.tableHeaderView = searchController.searchBar
}
但是,当我在视图中间有一个搜索栏(即其上方有一些其他元素)时,该代码无法正常工作,因为它告诉导航控制器内的搜索栏。我看到了以下问题,但对Swift没有可行的答案:
iOS 11 search bar jumping to top of screen
iOS 11 Searchcontroller jumps top of screen
我的ViewDidLoad设置参数是:
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
ResultsTable.tableHeaderView = searchController.searchBar
searchController.searchBar.barTintColor = MyGlobalVariable.themeMainColor
我在这里缺少什么?
答案 0 :(得分:-1)
试试这个:
if (@available(iOS 11, *)){
[searchVC.searchBar addObserver:self forKeyPath:@"frame" options: NSKeyValueObservingOptionNew context:nil];
}else{
[view addSubview:searchVC.searchBar];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
CGRect rect = [change[@"new"] CGRectValue];
if (rect.origin.y == 14) {
CGRect temp = rect;
temp.origin.y = 20;
[self.searchVC.searchBar setValue:@(temp) forKey:@"frame"];
}else if (rect.size.height == 56){
CGRect temp = rect;
temp.size.height = 50;
[self.searchVC.searchBar setValue:@(temp) forKey:@"frame"];
}
}