gpt4 book ai didi

ios - 为什么要调整此 UISearchBar 的大小?

转载 作者:可可西里 更新时间:2023-11-01 03:26:55 25 4
gpt4 key购买 nike

如下所示,当我点击搜索字段时,我的 UISearchBar 正在调整大小。它很好地动画覆盖了导航栏,然后弹出……它缩小了。

设置

UISearchBar 位于普通 UIView 中,设置为 tableHeaderView。我正在使用 UIView(而不是将 UISearchBar 设置为标题),因为我想在标题中放置其他 View 。

View 在 XIB 文件中定义,UISearchBar 锚定到其所有边框。约束似乎并不重要;如果我删除它们,会发生同样的问题。

实验

检查 Reveal 中的 View 层次结构告诉我 UIView 的大小正确并且 UISearchBar 的宽度为 1(?!)当发生这种情况时 .

作为实验,我将 UISearchBar 子类化并使 intrinsicContentSize 返回 {320,44}。有了这个 UISearchBar 正确显示,但是当我按 Cancel 时,我得到以下异常:

 *** Assertion failure in -[UITableView layoutSublayersOfLayer:], /SourceCache/UIKit_Sim/UIKit-2903.23/UIView.m:8540
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. UITableView's implementation of -layoutSubviews needs to call super.'

解决方法

如果我通过代码创建一切,它就可以正常工作。

_headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
searchBar.delegate = self;
[_headerView addSubview:searchBar];

_searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
_searchDisplayController.searchResultsDelegate = self;
_searchDisplayController.searchResultsDataSource = self;
_searchDisplayController.delegate = self;

_tableView.tableViewHeader = _headerView;

这是怎么回事?我显然不会再使用 nibs 来处理 UISearchBar,但我想了解到底发生了什么。

最佳答案

区别在于搜索栏的 translatesAutoresizingMaskIntoConstraints 值。对于基于 XIB 的 View ,它默认为 NO,对于基于代码的 View ,它默认为 YES。显然,搜索 Controller 假定值为 YES,并且在移植搜索栏时没有设置任何明确的约束。

在代码中将值设置为 YES 应该可以修复它(在本地验证)。

更新

如评论中所述,即使使用 translatesAutoresizingMaskIntoConstraints = YES, Controller 也不会在取消时将标题 View 恢复到其原始状态。但似乎确实有解决方法。您可以为标题 View 创建一个导出,并在 searchDisplayControllerDidEndSearch 中自行恢复它。我做了一个粗略的概念验证(并更新了我的示例项目):

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
self.tableView.tableHeaderView = self.headerView;
[self.searchBar removeFromSuperview];
self.searchBar.frame = CGRectMake(0, 20, 320, 44);
[self.headerView addSubview:self.searchBar];
}

关于ios - 为什么要调整此 UISearchBar 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21419992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com