Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding search bar programmatically to tableview in swift

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?

like image 308
Berk Kaya Avatar asked Jul 21 '16 15:07

Berk Kaya


1 Answers

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...
}
like image 62
Marco Castano Avatar answered Oct 12 '22 08:10

Marco Castano