2015-08-21 71 views
3

我想實現一個類似於聯繫人iOS應用程序的用戶界面,在那裏你有一個UISearchBar錨定在表視圖的頂部(如果你添加它作爲表視圖標題它會與內容一起滾動),並且當您開始搜索時,搜索欄會佔據導航欄的空間。使UISearchBar不滾動像在聯繫人應用程序

我正在使用UISearchController的搜索欄。

已嘗試在表視圖頂部添加容器視圖,並以編程方式向其添加搜索欄,但問題是當搜索欄轉到導航欄的位置時(由UISearchController自動完成)其寬度大於屏幕... enter image description here

這在模擬器和設備中都會發生。

任何(最好不哈克)的方式來實現這一點?

回答

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]]; 
} 
相關問題