如何修复iOS 11搜索栏在选择(Swift)上跳到屏幕顶部? [英] How to fix iOS 11 search bar jumping to top of screen on select (Swift)?
问题描述
具体来说,对于iOS 11(而不是之前的操作系统),当您点击搜索栏开始输入时,它会跳转到屏幕顶部。
Specifically, with iOS 11 (and not previous OS), when you tap a search bar to start typing, it jumps to the top of the screen.
I可以通过使用此代码在搜索栏已经靠近屏幕顶部时解决此问题:
I can fix this when the search bar is already near the top of the screen by using this code:
if #available(iOS 11, *) {
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
} else {
BugsTable.tableHeaderView = searchController.searchBar
}
但是,当我在视图中间有一个搜索栏时(即其他一些元素位于其上方) ),该代码将无法正常工作,因为它告诉导航控制器内的搜索栏。我看到了以下问题,但Swift没有合适的答案:
But, when I have a search bar in the middle of a view (i.e some other element is above it), that code won't work as it is telling the search bar inside the navigation controller. I saw the following questions, but no working answer for Swift:
iOS 11 Searchcontroller跳转到屏幕顶部
我的ViewDidLoad设置参数是:
My ViewDidLoad setup parameters are:
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
ResultsTable.tableHeaderView = searchController.searchBar
searchController.searchBar.barTintColor = MyGlobalVariable.themeMainColor
我在这里缺少什么?
推荐答案
试试这个:
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"];
}
}
这篇关于如何修复iOS 11搜索栏在选择(Swift)上跳到屏幕顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!