iOS 11搜索栏跳到屏幕顶部

13

我有一个UITableView,我将其标题设置为搜索栏。

tableView.tableHeaderView = searchController.searchBar

一切都按计划进行,直到你点击它,它似乎从tableView中脱离出来,跳到屏幕顶部。tableView 行保持在原地。为什么iOS 11会这样做而iOS 10不会呢?


无法重现,将表视图的表头视图设置为搜索控制器的搜索栏在iOS 11中仍然可以正常工作。 - matt
5个回答

15

鼓励采用在iOS 11上展示搜索栏/搜索控制器的新方法。以下是我所做的:

    if #available(iOS 11.0, *) {
        navigationItem.searchController = searchController
    } else {
        tableView.tableHeaderView = searchController.searchBar
    }

感谢@Simon Wang!一直在寻找这个解决方案!对于那些想要始终显示搜索栏的人,请添加: navigationItem.hidesSearchBarWhenScrolling = NO; - Bionicle

4

这是我在 Stack Overflow 上的第一篇帖子,希望我做得对。

我曾经遇到过完全相同的问题,很难找到解决方案。但现在我通过子类化 UISearchController 已经成功解决了它。

这个子类有两个属性:

var customDelegate : CustomSearchControllerDelegate!
var searchBarWithCustomSize : UISearchBar!

因此,我现在可以使用自定义searchController的新属性searchBarWithCustomSize,而不是使用UISearchController的searchBar。代码如下:

tableView.tableHeaderView = customSearchController.searchBarWithCustomSize

这使得搜索栏在激活时能够正确地工作。使用 searchBarWithCustomSize,您还可以获得更多自由,例如在需要时更改其框架等。
在我的实现中,我需要委托知道搜索栏文本字段何时已更改,但我想委托的使用取决于您的情况。

1
你能为我们发布你整个类的代码吗?谢谢。 - Chris Paveglio
如果您展示一些代码或代码工作流程,那将非常有帮助。 - The iCoder

2
我遇到了完全相同的问题——在iOS11上,UISearchBar 的跳跃行为很奇怪,而在iOS10上一切正常。关于上面 Simon Wang 的建议——我遇到的问题是我没有在 UIViewController 中定义我的 UISearchBar,而是在另一个 UITableViewCell 中,因此我无法访问 navigationItem 并以那种方式呈现我的搜索栏。

不管怎样,在尝试了很多次后,我唯一能使事情正常工作的方法就是彻底放弃使用 UISearchController 和相关的代理。

我在 Interface Builder 中定义了一个 UISearchBar,并根据需要定义其布局约束。然后,我使其父类符合 UISearchBarDelegate 并执行 searchBar.delegate = self

接下来,我添加了一堆代理方法来捕获搜索栏中的内容更改,并相应地更新我的表格结果:

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {  
   filterContentForSearchText(self.searchBar.text!)
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
   filterContentForSearchText(self.searchBar.text!)
   self.searchBar.resignFirstResponder()
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
   filterContentForSearchText(self.searchBar.text!)
}

现在生活又恢复了美好。希望这能帮到你!


我知道这已经过去几年了,但是这个解决方案对我非常有用,因为我没有导航栏。感谢分享! - Floyd Resler

0

试试这个。

if #available(iOS 11.0, *) {
    searchBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接