ios - 在搜索栏上键入会破坏布局

标签 ios swift uinavigationbar uisearchbar

我有一个 TableView :

tableView = UITableView()
view.addSubview(tableView)

tableView.translatesAutoresizingMaskIntoConstraints = false
let constraints = [tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.heightAnchor.constraint(equalToConstant: view.frame.height * 0.6)]
NSLayoutConstraint.activate(constraints)

我的 searchController 看起来像:

func setupSearchController() {
    searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = self
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Search for a candy"
    navigationItem.searchController = searchController
    definesPresentationContext = true
}

第一次加载时一切正常。但是,当我点击搜索栏在那里输入时,我的搜索栏移至顶部,导航栏变小,它破坏了我的布局,并且 tableView 和 searchBar 之间出现空白:

enter image description here

当导航栏大小发生变化时,如何改善上下移动 tableView 的约束?

最佳答案

您必须更改表格 View 的顶部约束。 尝试替换这 2 个约束

tableView.topAnchor.constraint(equalTo: searchController.searchBar.bottomAnchor), 
tableView.topAnchor.constraint(equalTo: view.topAnchor)

有了这个

tableView.topAnchor.constraint(equalTo: view.topAnchor)

自动内容插入调整将完成剩下的工作。

另请注意,在 TableView 约束列表中,您没有前导/水平位置约束。我建议也添加这个约束

tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor)

关于ios - 在搜索栏上键入会破坏布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52254459/

相关文章:

ios - UITableViewCell 子类中 View 的角半径

ios - 使用 UIKit Dynamics 动画自动布局支持 View

ios - 导航栏在 iPhone 4 (iOS 7.1.2) 中消失

ios - 如何在向下滚动时隐藏导航栏和工具栏? Swift(如 myBridge 应用程序)

ios - 从字符串中提取货币和价格值

ios - 如何将 ScrollView 与 CollectionView 一起使用

ios - Swift 内存布局

ios - 我可以在 iTunes 中发布具有不同名称和图标的应用程序,并在应用程序中发布具有不同名称和图标的应用程序吗?

swift - 在 Swift 中,导航栏消失并且永远不会回来

ios - JSON 数据未加载到 UITableView 中