2015-04-23 94 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

相關問題