使UISearchBar不像在联系人应用

时间:2015-08-21 20:59:57

标签: ios uitableview uisearchbar uisearchcontroller

我正在尝试实现类似于Contacts iOS应用程序的UI,其中您将UISearchBar锚定在表视图的顶部(如果您将其添加为表视图标题,它将与内容一起滚动),以及何时你开始搜索搜索栏会占用导航栏的空间。

我正在使用UISearchController的搜索栏。

尝试在表格视图的顶部添加容器视图,并以编程方式添加搜索栏,但问题是当搜索栏转到导航栏的位置时(由UISearchController自动完成)宽度大于屏幕...... enter image description here

这在模拟器和设备中都会发生。

任何(最好是非hacky)方式来实现这个目标?

1 个答案:

答案 0 :(得分:1)

请勿使用UITableViewController,使用标准UIViewController并自行添加searchBartableview

以下是示例代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.translatesAutoresizingMaskIntoConstraints = NO;
    searchBar.delegate = self;
    [searchBar sizeToFit];

    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.translatesAutoresizingMaskIntoConstraints = NO;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.contentInset = UIEdgeInsetsMake(searchBar.frame.size.height, 0.0, 0.0, 0.0);
    [tableView reloadData];

    [self.view addSubview:tableView];
    [self.view addSubview:searchBar];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:searchBar attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:searchBar attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:searchBar attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:tableView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:tableView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tableView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];
}