【发布时间】:2019-04-16 09:34:48
【问题描述】:
我们很久以前就为 iOS 5 开发了一个应用程序,我们在 storyboard 上使用了“搜索栏和搜索显示控制器”对象。由于iOS8 UISearchDisplayController 是deprecated,我正在尝试使用UISearchController 删除现有的“搜索栏和搜索显示控制器”。
由于UISearchController 在界面上的“对象库”中不可用,我已使用以下代码以编程方式将其添加到interface 上的UIView:
//Set up Search Controller
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = (id)self;
self.searchController.dimsBackgroundDuringPresentation = YES;
self.searchController.searchBar.delegate = self;
//Adding as subview to UIView 'searchBarContainer'
[self.searchBarContainer addSubview:self.searchController.searchBar];
[self.searchBarContainer bringSubviewToFront:self.searchController.searchBar];
self.definesPresentationContext = YES;
self.extendedLayoutIncludesOpaqueBars = YES;
并设置'searchController'的frame等于UIView如下:
UISearchBar *ctrlSearchBar = self.searchController.searchBar;
ctrlSearchBar.frame = CGRectMake(0, 0, self.searchBarContainer.frame.size.width, self.searchBarContainer.frame.size.height);
searchBar 的大小很好,但是当它专注于点击它时,'searchBar' 的宽度会自动增加。
我什至尝试使用 NSLayoutConstraints 但没有解决问题。 任何人都可以帮助如何修复“UISearchController.searchBar”的大小,即使它是集中的?
【问题讨论】:
-
您有
UITableView的结果吗?如果是 - 您可以将搜索控制器设置为tableHeaderView吗?另一种选择是直接使用UISearchBar而不使用UISearchController。 -
@surToTheW 即使将 UISearchController 设置为 tableHeaderView,我在聚焦时也遇到了与搜索栏相同的大小问题。搜索栏的宽度超过了设备宽度。关于直接使用 UISearchBar,我认为我们可以使用的唯一委托是 textDidChange。 textDidChange 是否更可取,而不是使用 UISearchController 的“updateSearchResults”委托?我不知道,但许多开发人员建议仅在需要将 UISearchBar 与 UITableView 一起使用时才使用 UISearchController。
-
我试过了,当表格视图的宽度小于屏幕的宽度时,搜索栏的行为很奇怪 - 超过表格视图的宽度或有时向上移动,但留在视图控制器中尺寸。所以我为当前的一个子视图控制器制作了一个子视图控制器,将其宽度设置为小于屏幕尺寸,并在那里添加了表格视图和搜索控制器。如果这是您的选择,您必须设置
self.definesPresentationContext = YES;并且搜索栏也设置为 tableHeaderView,如下所示:self.tableView.tableHeaderView = self.searchController.searchBar; -
@surToTheW 太棒了!这可能是解决方案。我会检查并回复你。
-
@surToTheW 工作就像一个魅力!非常感谢你!我不知道如何将您的回复标记为答案。但我相信这是正确的答案。
标签: ios objective-c xcode uisearchcontroller