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.
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.
Simply try this one :
override func viewDidLoad() {
super.viewDidLoad()
makeSearchBar()
}
func makeSearchBar() {
searchBar = UISearchBar()
searchBar.sizeToFit()
navigationItem.titleView = searchBar
}
Hope it will help you.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With