I have an textfield which represents an tableview as its inputview. I want to add 2 things to this tableview.
1) add a search bar.
2) add cancell button to top of tableview.
class enterYourDealVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UISearchResultsUpdating {
var tableView: UITableView = UITableView()
let searchController = UISearchController(searchResultsController: nil)
var dealAirports = [
airPorts(name: "Airport1", shortcut: "AP1")!),
airPorts(name: "Airport2", shortcut: "AP2")!)
]
var filteredAirports = [airPorts]()
//view did load
tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
toTextField.inputView = self.tableView
//here is my search function
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredAirports = dealAirports.filter { ap in
return ap.name.lowercaseString.containsString(searchText.lowercaseString)
}
tableView.reloadData()
}
}
The problem is with this code, it doesn't search. Also when I click the search bar it dismiss the tableview and returns me back to viewcontroller. How can I fix this?
and how can I add cancel button to this tableview?
This will add a SeachBar
lazy var searchBar:UISearchBar = UISearchBar()
override func viewDidLoad()
{
searchBar.searchBarStyle = UISearchBar.Style.default
searchBar.placeholder = " Search..."
searchBar.sizeToFit()
searchBar.isTranslucent = false
searchBar.backgroundImage = UIImage()
searchBar.delegate = self
navigationItem.titleView = searchBar
}
func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String)
{
...your code...
}
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