2
votes

I have UISearchBar in my app. I set it as table header view. When text begin editing I want to set search bar as subview of my viewController. Search bar adding to viewController's view correctly, but it's frame is incorrect. This is my code:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
   UITableView *tableView = ((UITableView *)[((SectionViewController *)sharedInstance.currentViewController).view viewWithTag:1111]);
    [tableView reloadData];

    if([searchBar.text isEqualToString:@"Filter..."])
    {
        searchBar.text = @"";
        for(UIView *subView in searchBar.subviews){
            if([subView isKindOfClass:UITextField.class]){
                [(UITextField*)subView setTextColor:[UIColor blackColor]];
            }
        }
    }
    [((SectionViewController *)sharedInstance.currentViewController).view addSubview:searchBar];
    [searchBar setFrame:CGRectMake(0, 20, 320, 38)];

    [((SectionViewController *)sharedInstance.currentViewController).navigationController setNavigationBarHidden:YES animated:YES];
    [searchBar setShowsCancelButton:YES animated:YES];
}

I want to set frame (0, 20, 320, 38), but I get (0, 0, 320, 38). Also, initial frame of searchBar is (0, 0, 320. 38). Please, tell me why I get this?

3
If you are not going to use a "UISearchDisplayController", try by using a UITextField, you can make it look exactly as an UISerchBar and it will be more customisableCamo

3 Answers

2
votes

UISearchBar is weird. You cannot freely set its frame. This is due to the internal implementation.

0
votes

I add the UISearchBar like this to my ViewController which is derived from UITableViewController:

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,0,self.tableView.frame.size.width,44)];
searchBar.placeholder = @"Search for Groups";
searchBar.delegate = self;
self.searchController = [[UISearchDisplayController alloc]
        initWithSearchBar:searchBar
       contentsController:self];
self.searchController.delegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
self.tableView.tableHeaderView = self.searchController.searchBar;
0
votes

A view can't be in two places at once. You can't coherently add the same search bar as a subview to your view controller's view at the same time that it is a table view's header. Why not make a different search bar?