【问题标题】:Why won't my UISearchBar obey constraints?为什么我的 UISearchBar 不服从约束?
【发布时间】:2016-12-18 12:21:50
【问题描述】:

在我的 iOS 应用程序中,我有一个导航栏,由 UIStackView 中的 UISearchBarUIButton 组成。由于我无法为UISearchController 编写故事板,因此我在堆栈视图中有一个空白UIView,我将UISearchBar 添加为子视图。这是我的故事板的样子:

这是我添加搜索栏的代码

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,如下所示: 我怎样才能让UISearchBar 像这样以UIButton 结尾?

【问题讨论】:

  • 尝试将按钮移动到uiobject列表中包装视图上方
  • @SaintThread 将UIButton 放在搜索栏前面。
  • 对不起,我误解了这个问题,你能展示使用包装视图的约束吗?也许你有父视图的尾随而不是按钮
  • 奇怪的是:如果我点击搜索栏并调出键盘,一切正常。我假设那是因为它正在更新视图。有没有办法强制视图更新?这可能会解决我的问题
  • @SaintThread 我对包装视图没有限制,因为它位于堆栈视图中。堆栈视图中不需要约束

标签: ios swift uiview autolayout uisearchbar


【解决方案1】:

尝试替换:

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)

这将允许您在搜索栏附近添加一个自定义按钮。

【讨论】:

  • Swift 3 不允许我将 nil 传递给选项
  • 尝试一个空数组:[]
  • 它使用了空数组,但现在应用程序崩溃了
  • 'NSInvalidArgumentException',原因:'-[UISearchController nsli_superitem]:无法识别的选择器发送到实例 0x7f8050e071c0'
  • 这是我希望 Apple 让我们的故事板 UISearchController 的地方。这将是第三个不支持 UISearchController 故事板的 Xcode
【解决方案2】:

我遇到了同样的问题,在将其添加到我的视图后(就在 addSubview() 行之后),我能够通过调用 searchController.searchBar.sizeToFit() 来修复它。您之前可能必须运行wrapperView.layoutIfNeeded(),所以是这样的:

wrapperView.addSubview(searchController.searchBar)
wrapperView.layoutIfNeeded()
searchController.searchBar.sizeToFit()

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    相关资源
    最近更新 更多