隐藏 UITableView 搜索栏

2023-12-29

我有一个 UITableViewController ,它以标准方式设置了 UISearchDisplayController (搜索栏位于 tableView 内)。我希望搜索栏一开始是隐藏的 - 真正隐藏,而不仅仅是滚动消失就像在这个解决方案中一样 https://stackoverflow.com/questions/1081381/iphone-hide-uitableview-search-bar-by-default。然后,我想在用户按下按钮时显示搜索 UI,并在用户选择搜索中找到的项目之一后再次隐藏它(真正隐藏它)。

这是几乎可以工作的代码:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.searchDisplayController.searchBar.prompt = @"Add an item";
    self.searchDisplayController.searchBar.placeholder = @"Type the item name";

    // i do this to trigger the formatting logic below
    [self.searchDisplayController setActive:YES animated:NO];
    [self.searchDisplayController setActive:NO animated:NO];
    // rest of my view will appear
}

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller {

    NSTimeInterval duration = (self.isViewLoaded && self.view.window)? 0.3 : 0.0;
    __block CGFloat searchBarHeight = controller.searchBar.frame.size.height;

    [UIView animateWithDuration:duration animations:^{
        self.tableView.contentOffset = CGPointMake(0, searchBarHeight);
        self.tableView.contentInset = UIEdgeInsetsMake(-searchBarHeight, 0, 0, 0);  // trouble here, I think
    } completion:^(BOOL finished) {
        controller.searchBar.hidden = YES;
    }];
}

to show

- (IBAction)pressedAddButton:(id)sender {

    self.searchDisplayController.searchBar.hidden = NO;
    [self.searchDisplayController setActive:YES animated:YES];
}

我认为我正确设置了内容插图,但它的行为出乎意料:使用所示的代码,表格允许内容向上移动太远,即只有两个不是很高的行,我可以向下滚动,将这两行中的大部分推到桌子顶部上方......就像没有底部反弹一样。当我注释掉 contentInset 行时,表格让我将内容拉得太远,在第 0 行上方留下一个大间隙,大概是搜索栏隐藏的位置。

如果有人可以提供帮助,我非常感激。


对于可能遇到此问题的任何其他人(似乎没有人)-

我能找到的唯一前进方法是放弃 UITableViewController,转而使用带有 uiview 的 UIViewController,其子级是表视图和搜索栏。

我按上面的方式管理布局:

- (void)setSearchHidden:(BOOL)hidden animated:(BOOL)animated {

    UISearchBar *searchBar = self.searchDisplayController.searchBar;
    CGFloat searchBarHeight = searchBar.frame.size.height;

    CGFloat offset = (hidden)? -searchBarHeight : searchBarHeight;
    NSTimeInterval duration = (animated)? 0.3 : 0.0;

    [UIView animateWithDuration:duration animations:^{
        searchBar.frame = CGRectOffset(searchBar.frame, 0.0, offset);
        self.tableView.frame = UIEdgeInsetsInsetRect(self.tableView.frame, UIEdgeInsetsMake(offset, 0, 0, 0));
    } completion:^(BOOL finished) {if (!hidden) [searchBar becomeFirstResponder];}];
}

除非在 add 函数开始和结束时调用的方法。

(大约每年两次,我得出这样的结论:UITableViewController 带来的麻烦大于它的价值。然后,以大约相同的频率,我忘记了我学到的这一点)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

隐藏 UITableView 搜索栏 的相关文章

随机推荐