Put search bar in nav bar programmatically

时光毁灭记忆、已成空白 提交于 2020-01-03 05:23:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!