【问题标题】:UISearchBar subview of UITableViewHeader?UITableViewHeader 的 UISearchBar 子视图?
【发布时间】:2014-12-16 19:50:34
【问题描述】:

我想将 UISearchBar 添加到已经有标题视图的 UITableView 中。当我尝试将搜索栏添加到现有的标题视图时,它会一直工作,直到我点击它,此时我得到The view hierarchy is not prepared for the constraint,这似乎是因为搜索栏不是 tableview 的直接子视图,所以当 UISearchController尝试更新它不能更新的约束。

我发现解决此问题的唯一方法是将表格视图标题设为搜索栏,然后一切正常,但当然我会丢失已经在标题视图中的其他视图。

【问题讨论】:

    标签: ios uitableview uisearchbar uisearchcontroller


    【解决方案1】:

    为了避免这种行为,我将搜索栏放在容器 UIView 中。将约束应用于此容器视图,并为容器内的搜索栏使用自动调整大小的掩码。

    // Configure header view
    UIView *headerView = ...
    ...
    
    // Create container view for search bar
    UIView *searchBarContainer = [UIView new];
    searchBarContainer.translatesAutoresizingMaskIntoConstraints = NO;
    [searchBarContainer addSubview:self.searchBar];
    [headerView addSubview:searchBarContainer];
    self.searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    // Apply constraints involving searchBarContainer
    [headerView addConstraint: ...];
    ...
    
    // Then add header to table view
    self.tableView.tableHeaderView = headerView;
    

    【讨论】:

    • 哇,谢谢!我花了几天的时间搜索和尝试各种解决方法,直到找到你的帖子。由于我使用的是 UISearchController,我遇到了一个奇怪的问题,即 UISearchBar 被添加到 searchBarContainer,但是当我签入 viewWillAppear 时它不再存在,所以我必须再次手动添加它。在将 UISearchBar 重新添加为容器中的子视图后,目前正在与初始帧怪异作斗争,但这绝对是正确的方向。
    • 你可能需要在 viewWillAppear 中添加这个: if (self.searchBarContainerView.subviews.count == 0) { [self.searchBarContainerView addSubview:self.searchController.searchBar]; // 还要修正帧高 CGRect frame = self.searchBarContainerView.frame; frame.size.height = 44.0f; self.searchBarContainerView.frame = 框架; }
    猜你喜欢
    • 2014-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多