保留 UISearchBar 的边距

Preserve margins for UISearchBar

我正在尝试创建 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)

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

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

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

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

问题是您以编程方式创建视图并使用自动调整掩码。

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

By default, the property is set to true for any view you programmatically create.

简单 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)
            ])
    }
}

我最终得到以下解决方案:在每次呈现和关闭搜索控制器后更新搜索栏框架,并在 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
}