UISearchBar increases navigation bar height in iOS 11

后端 未结 19 1584
醉酒成梦
醉酒成梦 2020-11-28 02:47

I have my UISearchBar being part of the navigation bar like:

 let searchBar = UISearchBar()
 //some more configuration to the search bar
 .....
         


        
19条回答
  •  天涯浪人
    2020-11-28 03:21

    Hi to the people who uses UISearchController and then attaching its UISearchBar to the navigationItem.titleView. I've spend a crazy 4-5 hours of my day to solve this. Following the iOS 11+ recommended approach, which is putting the searchController to the navigation.searchController is not just right for my case. The screen that has this searchController/searchBar has a backButton, a custom one.

    I have tested this in iOS 10, iOS 11, and 12. In different devices. I just had to. I can't go home without solving this demon. This is the most perfect I could do for today, given my tight deadline.

    So I just wanna share this hard work that I did, it's up to you to put everything into where ever you want (ex. variables in your viewModel). Here it goes:

    In my first screen (say home screen, that does not have this search controller), I have this in my viewDidLoad().

    self.extendedLayoutIncludesOpaqueBars = true
    

    In my second screen, the one that has the searchController, I have this in my viewDidAppear.

    override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated)

        let systemMajorVersion = ProcessInfo.processInfo.operatingSystemVersion.majorVersion
        if systemMajorVersion < 12 {
            // Place the search bar in the navigation item's title view.
            self.navigationItem.titleView = self.searchController.searchBar
        }
    
        if systemMajorVersion >= 11 {
    
            self.extendedLayoutIncludesOpaqueBars = true
    
            UIView.animate(withDuration: 0.3) {
                self.navigationController?.navigationBar.setNeedsLayout()
                self.navigationController?.navigationBar.layoutIfNeeded()
            }
    
            self.tableView.contentInset = UIEdgeInsets(top: -40, left: 0, bottom: 0, right: 0)
    
            if self.viewHadAppeared {
                self.tableView.contentInset = .zero
            }
        }
    
        self.viewHadAppeared = true // this is set to false by default.
    }
    

    and here's my searchController's declaration:

    lazy var searchController: UISearchController = {
        let searchController = UISearchController(searchResultsController: nil)
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.textField?.backgroundColor = .lalaDarkWhiteColor
        searchController.searchBar.textField?.tintColor = .lalaDarkGray
        searchController.searchBar.backgroundColor = .white
        return searchController
    }()
    

    So I hope this helps someone someday.

提交回复
热议问题