2017-09-25 19 views
2

具體來說,在iOS 11(而不是以前的操作系統)中,當您點擊搜索欄開始輸入時,它會跳轉到屏幕頂部。如何修復iOS 11搜索欄跳到屏幕頂部選擇(斯威夫特)?

我可以解決這個問題時,搜索欄已接近屏幕的頂端通過使用此代碼:

if #available(iOS 11, *) { 
    navigationItem.searchController = searchController 

    navigationItem.hidesSearchBarWhenScrolling = false 
} else { 
    BugsTable.tableHeaderView = searchController.searchBar 
} 

但是,當我有一個看法中間的搜索欄(即其他一些元素在它上面),那個代碼將不會工作,因爲它告訴導航控制器內的搜索欄。我看到了下面的問題,但對於斯威夫特沒有工作答案:

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

試試這個:

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"]; 
     } 
    }