如何让UISearchBar始终保持在NavigationBar中

时间:2014-07-21 20:27:27

标签: ios uitableview uinavigationcontroller uisearchbar

我需要UISearchBar始终保持在NavigationBar中。但到目前为止self.searchDisplayController.displaysSearchBarInNavigationBar = YES;并没有这样做。当我第一次启动应用程序时,searchBar位于NavigationBar中。但是一旦我点击它,它就会在我的场景/屏幕中间自行拍摄并且永远不会离开。

这个问题是对How do I add storyboard-based Header and CustomTableCell to a “Search Bar and Search Display Controller”

的跟进

我的.h文件是

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate>

@end

和我的.m文件是

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,strong)NSMutableArray *data;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.searchDisplayController.displaysSearchBarInNavigationBar = YES;
    self.data=[[NSMutableArray alloc]init];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [_data count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CellIdentifier";

    // Dequeue or create a cell of the appropriate type.
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    // Configure the cell.
    cell.textLabel.text = [NSString stringWithFormat:@"Row %d", indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"Row %d: %@", indexPath.row, [_data objectAtIndex:indexPath.row]];
    return cell;
}

#pragma mark - delegate

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(mockSearch:) userInfo:searchString repeats:NO];
    return NO;
}

- (void)mockSearch:(NSTimer*)timer
{
    [_data removeAllObjects];
    int count = 1 + random() % 20;
    for (int i = 0; i < count; i++) {
        [_data addObject:timer.userInfo];
    }
    [self.searchDisplayController.searchResultsTableView reloadData];
}

@end

这就是整个计划。

0 个答案:

没有答案