ios ios - 1 month ago 9
iOS Question

Add search bar under the navigation title

Here is my code:

[self.navigationController.navigationBar setFrame:CGRectMake(0, 0, 500, 800)];
self.navigationItem.title = @"locations";
[self.navigationController.navigationBar setFrame:CGRectMake(0, 0, self.view.frame.size.width,110.0)];
UISearchBar *searchBar1 = [[UISearchBar alloc]initWithFrame:CGRectMake(10, 40, 240, 34)];
[self.navigationController.view addSubview:searchBar1];
elf.navigationItem.title = @"locations";
//self.navigationItem.titleView = searchController.searchBar;
self.navigationController.navigationBar.barTintColor = `Color grayColor];
self.definesPresentationContext = YES;


like that screen shot

Answer

Here you go..Try this code

self.navigationItem.title = @"locations"; 
UISearchBar *searchBar1 = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 34)]; 
[self.view addSubview:searchBar1];
 NSLayoutConstraint *contTop = [NSLayoutConstraint constraintWithItem:searchBar1 
                               attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom
                               multiplier:1.0 constant:0]; 

NSLayoutConstraint *consHeight = [NSLayoutConstraint constraintWithItem:searchBar1 attribute:NSLayoutAttributeHeight
                                 relatedBy:NSLayoutRelationEqual toItem:nil
                                 attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0  
                                 constant:34]; 

NSLayoutConstraint *contLeading = [NSLayoutConstraint constraintWithItem:searchBar1 attribute:NSLayoutAttributeLeading
                                  relatedBy:NSLayoutRelationEqual toItem:self.view
                                  attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]; 
NSLayoutConstraint *conttrailing = [NSLayoutConstraint constraintWithItem:searchBar1 attribute:NSLayoutAttributeTrailing
                                   relatedBy:NSLayoutRelationEqual toItem:self.view 
                                  attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]; 
[NSLayoutConstraint activateConstraints:@[contTop, consHeight,contLeading,conttrailing]];
[searchBar1 setTranslatesAutoresizingMaskIntoConstraints:NO]; 
[self.view layoutSubviews]; 
self.navigationItem.title = @"locations"; 
self.navigationController.navigationBar.barTintColor = [UIColor orangeColor]; 
searchBar1.barTintColor= [UIColor orangeColor]; 
self.definesPresentationContext = YES;