2015-04-23 90 views
2

我拿了一个UITableViewController并试图在其中添加UISearchDisplayController。我从互联网上阅读了很多代码,但不知道我的错在哪里。搜索视图始终显示在桌面上顶部

我的问题是为什么UISearchDisplayController不能始终粘在UITableView之上。

这里是我的代码

SearchView_controller.h 

@interface SearchView_controller : UITableViewController<UISearchBarDelegate,UISearchDisplayDelegate> 
@end 


SearchView_controller.m 

@interface SearchView_controller() 
{ 
    UISearchDisplayController *searchController; 
} 
@end 

@implementation SearchView_controller 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [email protected]"Test"; 

    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, self.tableView.frame.origin.y, self.tableView.frame.size.width, 44)]; 
    [searchBar sizeToFit]; 
    [searchBar setDelegate:self]; 

    searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar 
                   contentsController:self]; 
    [searchController setSearchResultsDataSource:self]; 
    [searchController setSearchResultsDelegate:self]; 
    [searchController setDelegate:self]; 

    [self.tableView setTableHeaderView:searchController.searchBar]; 

} 

-(void) scrollViewDidScroll:(UIScrollView *)scrollView { 
    UISearchBar *searchBar = searchController.searchBar; 
    CGRect rect = searchBar.frame; 
    rect.origin.y = MAX(0, scrollView.contentOffset.y); 
    searchBar.frame = rect; 
} 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return 30; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"searchview_customecell"; 
    searchview_customecell *cell = (searchview_customecell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    [email protected]"test"; 
    return cell; 
} 

searchview_customecell.h 


@interface searchview_customecell : UITableViewCell 
@property(nonatomic, weak) IBOutlet UILabel *lbl_name; 
@end 

searchview_customecell.m 

@implementation searchview_customecell 

- (void)awakeFromNib { 
    // Initialization code 
} 

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

    // Configure the view for the selected state 
} 

@end 
+0

尝试的UIViewController不是UITableViewController中检查也是这个例子做:http://useyourloaf.com/blog/2012/09/06/search-bar-table - 视图 - storyboard.html –

回答

2

这是更好地应对UIViewController而不是UITableviewController处理这种东西。

UITableViewController一样,查看是tableView,所以只要添加了searchBar,它就会被添加到tableView

对于这个问题,有两种可能的解决方案:

  1. 要么与UIViewController的替代Tableviewcontroller并把搜索栏在视图开始(不要在tableview中头添加它),其次是实现代码如下。

  2. 请点击此链接:UISearchDisplayController with UITableViewController

相关问题