保留UISearchBar的边距

时间:2018-09-02 21:18:10

标签: ios swift uikit uisearchbar uisearchcontroller

我正在尝试创建UISearchController并将其搜索栏放入容器视图。 searchView是插座。这是我的代码:

    let searchController = UISearchController(searchResultsController: nil)
    self.searchController = searchController

    let searchBarBackground = UIImage.roundedImage(UIImage.image(with: #colorLiteral(red: 0.5568627451, green: 0.5568627451, blue: 0.5764705882, alpha: 0.2), size: size), cornerRadius: cornerRadius)
    searchController.searchBar.setSearchFieldBackgroundImage(searchBarBackground, for: .normal)
    searchController.searchBar.searchTextPositionAdjustment = UIOffsetMake(8.0, 0.0)
    searchController.searchBar.searchBarStyle = .minimal
    searchController.searchBar.barStyle = .black
    searchController.searchBar.delegate = self

    searchView.addSubview(searchController.searchBar)

我不知道如何制作搜索栏以保留主视图的边距。当我尝试向容器视图添加约束并将搜索栏添加为子视图时,搜索栏不遵循尾随约束。

enter image description here

即使手动设置搜索栏框架等于viewDidLayoutSubviews中的内容视图界限也无济于事。仅当我将前导约束和尾随约束设置为0而不考虑超级视图边距时,它看起来才确定。但是从侧面看它只有8pt的页边距,我需要更多。

enter image description here

如何实现?也许可以更改搜索栏的默认边距?谢谢。

如果需要,可以从IB截取屏幕截图(这只是限制值为-8的边距以补偿搜索栏内部边距):

enter image description here

2 个答案:

答案 0 :(得分:1)

我得到了以下解决方案:在每次显示和关闭搜索控制器后以及在viewDidAppear(_:)中进行初始设置后,更新搜索栏框架。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    searchController?.searchBar.frame.size.width = searchView.bounds.width
}

func didPresentSearchController(_ searchController: UISearchController) {
    searchController.searchBar.frame.size.width = self.searchView.bounds.width
}

func didDismissSearchController(_ searchController: UISearchController) {
    searchController.searchBar.frame.size.width = self.searchView.bounds.width
}

答案 1 :(得分:0)

问题是您以编程方式创建了视图并使用了自动调整大小的蒙版。

https://developer.apple.com/documentation/uikit/uiview/1622572-translatesautoresizingmaskintoco

  

默认情况下,以编程方式创建的任何视图的属性都设置为true。

简单的UISearchBar示例:

class ViewController: UIViewController, UISearchBarDelegate {

    weak var searchBar: UISearchBar?

    override func viewDidLoad() {
        super.viewDidLoad()

        let searchBar = UISearchBar(frame: .zero)
        self.searchBar = searchBar
        searchBar.searchBarStyle = .minimal
        searchBar.barStyle = .black
        searchBar.delegate = self
        searchBar.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(searchBar)
        NSLayoutConstraint.activate([
            searchBar.topAnchor.constraint(equalTo: view.topAnchor, constant: 50.0),
            searchBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40.0),
            view.trailingAnchor.constraint(equalTo: searchBar.trailingAnchor, constant: 40.0),
        searchBar.heightAnchor.constraint(equalToConstant: 36.0)
            ])
    }
}