How to move search bar into the navigation bar using Swift?
Asked Answered
D

2

5

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.

Desouza answered 4/1, 2018 at 22:43 Comment(0)
B
5

Simply try this one :

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

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

Hope it will help you.

Bonni answered 5/1, 2018 at 9:45 Comment(0)
Z
1

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)
        }
    }
Zarf answered 18/4, 2018 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.