Adding UISearchBar in UINavigationBar

2.2k Views Asked by At

I Added UISearchBar in UINavigationBar and its showing also but the delegate methods are not working. My code is as follows:

MainViewController.h

@interface MainViewController : UIViewController<UISearchBarDelegate>  {

}

@property(nonatomic, readonly) UISearchBar *_searchBar;
@property(nonatomic, assign) id<UISearchBarDelegate> delegate;

MainViewController.m

-(void)viewDidLoad  {
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(320.0, 0.0, 320.0, 44.0)];
    _searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc]    
initWithCustomView:_searchBar];
    _searchBar.delegate = self;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText  {
    NSLog(@"textDidChange is firing with %@",searchText);
}

Its not showing even the typed text only! Please give me suggestions.Thank You!

1

There are 1 best solutions below

0
Yan On

You have to connect the search bar in interface builder to the code. It has to be an IBOutlet.

The code will look like

@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;

and you don't need to declare

@property(nonatomic, assign) id<UISearchBarDelegate> delegate;