Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move search bar into the navigation bar using Swift?

So I'm wondering how I can move the search bar in my app (which is currently displayed below the navigation bar, into the navigation bar.

Right now, I have a function called makeSearchBar(), which I call in viewDidLoad() to make the search bar. There is no storyboard or xib file. I would like to get rid of the title on the navigation bar and replace it with the search bar. However, when I use the methods given in other users' questions, either the search bar disappears or remains where it is.

enter image description here

This is the code for the search bar:

override func viewDidLoad() {
        super.viewDidLoad()
        makeSearchBar()
}

func makeSearchBar() {
        searchBar = UISearchBar()
        searchBar.delegate = self
        searchBar.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: 60)

       // searchBar.sizeToFit()

       //TRYING TO ADD TO NAV BAR
       navigationItem.titleView = searchBar

        searchBar.placeholder = "Search"

        view.addSubview(searchBar)
}

I'm also wondering how to make the top row that's supposed to make the battery info have a different background color.

If you have any suggestions, I would love to hear them. I am new to iOS and am not sure what I'm doing.

like image 851
RainyRun Avatar asked Jan 04 '18 22:01

RainyRun


2 Answers

Simply try this one :

override func viewDidLoad() {
        super.viewDidLoad()
        makeSearchBar()
}

func makeSearchBar() {
   searchBar = UISearchBar()
    searchBar.sizeToFit()
    navigationItem.titleView = searchBar
}

Hope it will help you.

like image 119
Mayur Avatar answered Nov 15 '22 03:11

Mayur


Try this code by calling the presentSearchController in viewDidLoad()

fileprivate func presentSearchController(initialSearchText searchText:String? = nil){
        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.text = searchText
        if #available(iOS 11.0, *){
            self.navigationItem.searchController = searchController
            searchController.isActive = true
        }
        else{
            present(searchController, animated: true, completion: nil)
        }
    }
like image 30
Syed Zahid Shah Avatar answered Nov 15 '22 04:11

Syed Zahid Shah