ios - 为什么成为第一响应者后我的 UISearchBar 的宽度为 0?

标签 ios swift autolayout uisearchbar nslayoutconstraint

我的 UIStackView 中有一个 UISearchBar,它带有一个按钮,类似于导航栏。这是它通常的样子:enter image description here 但是当它成为第一响应者时,UISearchBar 的宽度变为 0,它看起来像这样:enter image description here

现在我唯一的限制是右侧 UIButton 的宽度为 44pt,并且整个堆栈 View 固定在屏幕的顶部和两侧。这是控制台打印出来的内容: enter image description here

我对 NSLayoutConstraint 不是很流利,但显然有些东西与按钮上的 44pt 宽度约束冲突。为什么 UISearchbar 的宽度变为 0?

这是我的代码:

override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
    if presentationStyle == .expanded {
        searchController.searchBar.becomeFirstResponder()
        searchController.searchBar.tintColor = UIColor.white
    }
}

func didDismissSearchController(_ searchController: UISearchController) {
    requestPresentationStyle(.compact)
}

override func viewDidLoad() {
    super.viewDidLoad()
    configureSearchController()
}

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
    stackView.insertArrangedSubview(searchController.searchBar, at: 0)
    //This removes the hairline
    let color = addButton.backgroundColor
    searchController.searchBar.layer.borderWidth = 1
    searchController.searchBar.layer.borderColor = color?.cgColor

}

func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
    if presentationStyle == .expanded {
        return true
    } else {
        requestPresentationStyle(.expanded)
        return false
    }
}

我的 Storyboard按要求: enter image description here

最佳答案

I'm not very fluent in NSLayoutConstraint but clearly something is conflicting with the 44pt width constraint on the button. Why is the UISearchbar's width becoming 0?

您的输出显然对按钮的前缘有限制——但您说您只限制了按钮的宽度。输出表明您将按钮的前缘限制在堆栈 View 的前缘。

您当然可以将按钮的前缘限制在堆栈 View 的前缘,并将按钮设置为 44 宽——如果按钮位于搜索栏的左侧。但是,因为按钮位于搜索栏的右侧,所以按钮可以是 44 宽,也可以限制在堆栈 View 的前缘——但不能两者兼而有之。

因此,iOS 打破了 44 宽度限制,并将按钮一直延伸到左侧,使其与堆栈 View 的前缘对齐。

这不一定是结果。我想 Apple 可以对 Xcode 进行编程以忽略您拖动按钮的位置并仅服从约束,即移动按钮使其前缘和堆栈 View 的前缘对齐并给按钮宽度 44,因此将搜索栏移动到按钮的右侧。但是,显然 Apple 更重视水平堆栈 View 中项目的排序,即因为您将按钮放置在搜索栏的右侧,所以它就保留在那里。

关于ios - 为什么成为第一响应者后我的 UISearchBar 的宽度为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938559/

相关文章:

ios - 如何检查 ios url 连接中是否发生超时?

ios - parse.com 删除对象,顺便说一下,删除与之相关的对象

ios - Xcode 调试器中显示奇怪的值

swift - 如何从 firebase 异步加载数据并将其显示在 UICollectionView 中

ios - 以编程方式将 NSLayoutAttributeLeading Space 设置为 Superview 并带有一些警告

ios - UITableViewCell 的 UIButton subview 取消选择 UITableViewCell?

c# - 如何使用 Unity 为 iOS 应用程序自动设置关联域

ios - SceneKit 使用枢轴计算节点的顶点世界坐标

ios - 使用自动布局的横向布局不同

ios - 以编程方式创建约束时出错