UIsearchBar. Can't change frame

被刻印的时光 ゝ 提交于 2020-01-15 03:16:05

问题


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?


回答1:


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




回答2:


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;



回答3:


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?



来源:https://stackoverflow.com/questions/21025982/uisearchbar-cant-change-frame

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