问题
I am trying to place a search bar in a navigation bar using the following code:
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(-5.0, 0.0, 320.0, 44.0)];
searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
UIView *searchBarView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 310.0, 44.0)];
searchBarView.autoresizingMask = 0;
searchBar.delegate = self;
[searchBarView addSubview:searchBar];
self.navigationItem.titleView = searchBarView;
It does place the search bar in the nav bar but does not cover the buttons on either side. It also does not have a cancel option.
I would prefer to have it look like this:
Can anyone suggest how to adjust the above code to do that?
Thanks in advance for any suggestions.
回答1:
in One of my project i did the same using below code hope it will help you :
-(void)addSearchBar{
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(35, -10, 285, 64)];
self.navigationItem.rightBarButtonItems=nil;
[self.searchBar setShowsCancelButton:YES];
for (id subView in ((UIView *)[self.searchBar.subviews objectAtIndex:0]).subviews) {
NSLog(@"subView====%@", subView);
if ([subView isKindOfClass:[UITextField class]]) {
UITextField *textField = subView;
textField.keyboardAppearance = UIKeyboardAppearanceAlert;
break;
}
if([subView isKindOfClass:[UIButton class]]){
UIButton* cancelBtn = (UIButton*)subView;
cancelBtn.frame=CGRectMake(cancelBtn.frame.origin.x, cancelBtn.frame.origin.x, 30, 30);
[cancelBtn setTitle:@"" forState:UIControlStateNormal];
[cancelBtn setImage:[UIImage imageNamed:@"btn_cancel_h.png"] forState:UIControlStateNormal];
[cancelBtn setEnabled:YES];
}
}
[[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:[UIColor whiteColor]];
self.searchBar.delegate=self;
[self.navigationController.navigationBar addSubview:self.searchBar];
}
来源:https://stackoverflow.com/questions/34611614/put-search-bar-in-nav-bar-programmatically