Layout of UISearchBar in UITableView header messed up after rotation

前端 未结 1 351
迷失自我
迷失自我 2021-01-14 12:28

I have a UITableView with a search bar inserted programatically into the table\'s headerView:

override func viewDidLoad() {

    su         


        
相关标签:
1条回答
  • 2021-01-14 12:50

    After noting that an inactive searchBar doesn't seem to have this problem, I have had success with saving the search bar state when the view disappears and restoring it before the view reappears.

    The sample code works fine with the following changes. Save the state:

    - (void)viewDidDisappear:(BOOL)animated
    {
        if (self.searchController.active && self.searchController.searchBar.text.length > 0) {
            self.savedSearch = self.searchController.searchBar.text;
            [self disableSearch];
        } else if (self.searchController.active) {
            // empty search field - this won't get restored
            [self disableSearch];
        }
        [super viewDidDisappear:animated];
    }
    
    - (void)disableSearch
    {
        if (self.searchController.isActive) {
            self.searchController.searchBar.text = @"";
            self.searchController.active = NO;
        }
    }
    

    And restore:

    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    
        if (self.savedSearch) {
            NSLog(@"RESTORED SEARCH");
            self.searchController.searchBar.text = self.savedSearch;
            self.searchController.searchBar.showsCancelButton = YES;
            self.searchController.active = YES;
            self.savedSearch = nil;
        }
    }
    

    This seems to work fine whether or not self.searchController.hidesNavigationBarDuringPresentation is set (although if true there is some animation on returning to the view).

    0 讨论(0)
提交回复
热议问题