Search bar is not getting fixed on iPhone

2019-08-23 01:52发布

I've two issues:

  1. I have a search bar in my iPhone screen. When I scroll my screen then my searchbar also gets scrolled. I want to fix this or make it absolute.
  2. Searching is not working like If I enter A then I should get all words that start with alphabet A.

Code that I'm trying:

- (void)viewDidLoad {
    [super viewDidLoad];
    const NSInteger searchBarHeight = 45;
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0,
    self.tableView.frame.size.width, searchBarHeight)];
    searchBar.delegate = self;
    self.tableView.tableHeaderView = searchBar;
    [searchBar release];
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Refresh" 
    style:UIBarButtonItemStyleBordered target:self action:@selector(onAddContact:)];
    self.navigationItem.rightBarButtonItem = addButton;
    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:20.0];
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor whiteColor]; // change this color
    self.navigationItem.titleView = label;
    label.text = NSLocalizedString(@"All Contacts", @"");

    [label sizeToFit];
    content = [DataGenerator wordsFromLetters];
    indices = [[content valueForKey:@"headerTitle"] retain];
}

2条回答
forever°为你锁心
2楼-- · 2019-08-23 02:30

Here when you scroll the UITableView at that time also UISearchBar scrolled because you add UISearchBar as a headerview of UITableView see this line..

self.tableView.tableHeaderView = searchBar;

so its scroll with UITableView , here for fix the UISearchBar just add as a subview of self.view with frame but outside from UITableView For Example..

[yourSearchBar setFrame:CGRectMake(0, 0, 320, 44)];
[self.view addSubview:yourSearchBar];

For more information, See bellow links with tutorials and demo for UISearchBar with UITableView

  1. filtering-a-uitableview-with-a-uisearchbar-using-core-data
  2. connect-uitableview-with-uisearchbar // see how can filter the array with searchbar textfield change event from this tutorial with - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText Method
查看更多
狗以群分
3楼-- · 2019-08-23 02:31

You need to separate the Search bar from Table View.Just add searchBar into view rather add it into table. The code is as follows:

[self.view addSubview:searchBar];

then add the table view.

For UISearchDisplayController example, please follow this tutorial: http://cocoabob.net/?p=67 or http://blog.mugunthkumar.com/coding/iphone-tutorial-uisearchdisplaycontroller-with-nspredicate/

Source code are also available. If you don't understand, please let me know. I have a project where all of these have already implemented.

查看更多
登录 后发表回答