uisearchbar - SearchController SearchBar 从 View 中消失

标签 uisearchbar xcode8 ios10 uisearchcontroller

我正在使用 Xcode 8(确切地说是版本 8.1 (8B62))为 iOS 10 进行开发,并且我正在尝试开发一个 View Controller ,在 上方显示固定的 searchBar TableView 。我已经有了初始布局,但是当我激活 searchBar 时,它从我的 View 中完全消失。

这是我的 View Controller 的 View 层次结构:

View 
| 
|---- UISearchBar 
| 
|---- UITableView

它看起来像这样:

initial layout

现在,问题来了。因为没有像 UISearchDisplayController 那样包含 UISearchController 的 Interface Builder 工具,所以我以编程方式将 searchBar 添加到我的界面中 View Controller 的 viewDidLoad 方法,我使用 searchController.searchBar 来替换我在 Storyboard中使用的临时 UISearchBar:

// attribute to store the searchController
var searchController: UISearchController!

// temporary searchBar from storyboard
@IBOutlet weak var tempSearchBar: UISearchBar!

...

override func viewDidLoad() {
    super.viewDidLoad()

    searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = self
    searchController.searchBar.frame = tempSearchBar.frame
    tempSearchBar.removeFromSuperview()
    view.addSubview(searchController.searchBar)
}

当我运行应用程序并激活附加到我的 searchControllersearchBar 对象时,它从 View 中消失:

activated searchBar

tableView 也发生奇怪的变化,但我的主要焦点是让 searchBar 留在 View 中。我尝试了一些不同的方法来使这项工作成功,但我的运气为零。任何帮助深表感谢。我只是觉得实现起来不应该那么困难。我可以使用 UISearchDisplayController 对象来完成此操作,但是这些对象已被弃用,我正在努力成为一名优秀的程序员而不是使用它。

最佳答案

我和你有同样的问题。问题源于尝试手动设置搜索栏的框架。您需要 Storyboard中的临时搜索栏吗?

要解决此问题,请删除设置框架的代码并将 Storyboard中的表格 View 连接到代码:

override func viewDidLoad() {
super.viewDidLoad()

searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
tableView.tableHeaderView = searchController.searchBar
}

关于uisearchbar - SearchController SearchBar 从 View 中消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40979409/

相关文章:

swift - swift 将 NSArray 传递给下一个 View Controller

ios - 如何检测 textDidChange : on UISearchBar was triggered by dictation

iphone - UISearchBar 文本字段中的自定义清除按钮

iphone - 用作 UINavigationBar titleVIew 时未调用 UISearchBar 委托(delegate)?

Facebook 登录错误 - Xcode 8 GM

ios - 由于信号 : Segmentation fault: 11 swift 3,命令失败

ios - UITapGestureRecognizer 在 Swift 的 SearchField 类中破坏了 UITableView didSelectRowAtIndexPath?

XCode 8 - 构建有效但存档失败 - React Native

ios - Firebase 数据库设置值 : or removeValue failed: permission_denied iOS

ios - 运动开始 :withEvent: not called in AppDelegate in iOS 10