首页 > 解决方案 > 如何在视图中的特定点添加子视图

问题描述

我正在向 tableView.tableHeaderView 添加一个 imageView 和 UISearchController.searchBar。但没有找到正确的方法在图像之后显示 searchBar。

    let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 333))
    let image = UIImageView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 269))
    image.image = #imageLiteral(resourceName: "map")
    view.addSubview(image)
    view.insertSubview(searchController.searchBar, at: 1)//insertSubview(searchController.searchBar, belowSubview: image)
    self.tableView.tableHeaderView = view

但结果是这样的。在此处输入图像描述 期望的结果就是这样。 在此处输入图像描述

标签: iosswifttableviewnstableheaderview

解决方案


如果您想在视图底部添加搜索栏 您可以以编程方式添加搜索栏并将其固定到视图底部

view.addSubview(searchBar)

searchBar.bottomAnchor.constraint(equalTo: view.trailingAnchor).isActive =true
searchBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
searchBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
searchBar.heightAnchor.constraint(equalToConstant: 50).isActive = true

最简单的方法


推荐阅读