在我的iOS应用程序中,我有一个导航栏,其中包含UISearchBarUIButton中的UIStackView。由于我无法将UISearchController放在情节提要中,因此我在堆栈视图中有一个空白的UIView,然后将UISearchBar添加为子视图。这是我的故事板的外观:ios - 为什么我的UISearchBar不遵守约束?-LMLPHP

这是我添加搜索栏的代码

override func viewDidLoad() {
    super.viewDidLoad()
    configureSearchController()
    print(wrapperView.bounds)
    print(searchController.searchBar.bounds)
}

func configureSearchController() {
    searchController = UISearchController(searchResultsController: nil)
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Search here..."
    searchController.searchBar.sizeToFit()
    searchController.searchBar.isTranslucent = false
    searchController.searchBar.delegate = self
    searchController.delegate = self
    searchController.searchBar.barTintColor = addButton.backgroundColor
    wrapperView.addSubview(searchController.searchBar)
    let color = addButton.backgroundColor
    searchController.searchBar.layer.borderWidth = 1
    searchController.searchBar.layer.borderColor = color?.cgColor
    searchController.searchBar.trailingAnchor.constraint(equalTo: addButton.leadingAnchor)
}

但是搜索栏超出了UIButton,如下所示:
ios - 为什么我的UISearchBar不遵守约束?-LMLPHP
我怎样才能使UISearchBar像这样在UIButton结尾?
ios - 为什么我的UISearchBar不遵守约束?-LMLPHP

最佳答案

尝试更换:

searchController.searchBar.trailingAnchor.constraint(equalTo: addButton.leadingAnchor)

与:
searchController.translatesAutoresizingMaskIntoConstraints = false
wrapperView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: nil, metrics: nil, views: ["subview": searchController]))
wrapperView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: nil, metrics: nil, views: ["subview": searchController]))

编辑:
否则,请尝试使用UISearchController:
searchController.searchBar.setImage(<image_name>, forSearchBarIcon: .Bookmark, state: .Normal)

这样您就可以在搜索栏附近添加自定义按钮。

关于ios - 为什么我的UISearchBar不遵守约束?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38901824/

10-10 22:25
查看更多