0

I am trying to add a search bar (with an IBAction method) to my viewController, but it is not showing up. Am I missing anything?

import UIKit

class SongrequestViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {



var tableView = UITableView()
var searchBar = UISearchBar()

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    tableView = UITableView(frame: CGRect(x: 10, y: 200, width: 370, height:400))
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    tableView.dataSource = self
    tableView.delegate = self
    self.view.addSubview(tableView)
    
    searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50))
    searchBar.searchBarStyle = UISearchBar.Style.prominent
    searchBar.placeholder = "Search for your song here..."
    searchBar.sizeToFit()
    searchBar.isTranslucent = false
    searchBar.delegate = self
    self.view.addSubview(searchBar)
}

The tableView is showing up, but not the search bar.

Angela C
  • 15
  • 6

1 Answers1

0

View's frame will not be set in viewDidLoad. So self.view.frame.size.width might not return the correct value in viewDidLoad.

searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50))

Try adding the searchbar in viewDidAppear.

To detect text changes in searchbar, confirm to UISearchBarDelegate in your SongrequestViewController and implement its delegate method.

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    print("search text: ", searchText)
}
Jithin
  • 913
  • 5
  • 6
  • Thanks, do you know how I would be able to add something similar or the same as an IB action method to the search bar? – Angela C Aug 10 '20 at 21:12
  • Thank you. Unfortunately, it did not work, but thanks anyways! I added another independent XIB file to my viewController to have the search bar show up. – Angela C Aug 11 '20 at 17:09