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

前端之家收集整理的这篇文章主要介绍了ios – 为什么我的UISearchBar在成为第一响应者之后的宽度为0?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的UIStackView中有一个UISearchBar,带有一个按钮,可以创建一个导航栏.这是它通常的样子:

enter image description here


但当它成为第一响应者时,UISearchBar的宽度变为0,它看起来像这样:

enter image description here

现在唯一的约束是右边的UIButton的宽度是44pt,整个堆栈视图固定在屏幕的顶部和侧面.这是控制台打印出来的:

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
    }
}

我的故事板按要求:
@L_403_3@

解决方法

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?

对于按钮前沿的输出显然有一个约束 – 但是你说你只限制了按钮的宽度.输出表示您将按钮的前沿约束到堆栈视图的前沿.

您当然可以将按钮的前沿限制在堆栈视图的前沿,并使按钮44变宽 – 如果按钮位于搜索栏的左侧.但是,因为按钮位于搜索栏的右侧,所以按钮可以是44宽或者可以约束到堆栈视图的前沿 – 但不能同时限制在两者之间.

因此,iOS打破了44宽度约束,并将按钮一直延伸到左侧,以便它与堆栈视图的前沿对齐.

这不一定是结果.我想Apple可以编程Xcode来忽略你拖动按钮的位置并且只是遵守约束,即移动按钮使其前缘和堆栈视图的前缘对齐,并给按钮宽度为44,因此将搜索栏移动到按钮右侧.但是,显然Apple更倾向于在水平堆栈视图中对项目的排序,即因为您将按钮放在搜索栏的右侧,这就是它保留的位置.

猜你在找的iOS相关文章