How to make sure the SearchBar Textfield is empty - swift

I have a SearchBar when i press the cancel button i have it set so that the textfield should have no text and all of my collection view cell's show
When the cancel button is tapped while there is still text in the TextField my collection view shows no cells until i go back into the search bar and press the delete button "X"
Would appreciate some help Thanks
Here is the code
print(" search button pressed")
navigationItem.titleView = searchBar
searchBar.searchTextField.backgroundColor = .black
searchBar.searchTextField.textColor = .white
searchBar.placeholder = "search for a contact"
searchBar.showsCancelButton = true
searchBar.becomeFirstResponder()
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem?.tintColor = .white
} else {
print(" cancel button pressed")
searchBar.searchTextField.text? = ""
navigationItem.titleView = nil
searchBar.showsCancelButton = false
navigationItem.rightBarButtonItem?.isEnabled = true
navigationItem.rightBarButtonItem?.tintColor = .purple
collectionView.reloadData()

Did you try assigning nil to searchBar.searchTextField.text? Maybe that can make a difference.

here's how I would check if I've done my implementation properly. Make sure I'm calling necessary delegate methods for UISearchBarDelegate and handle filter there.
extension MyViewController: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = true
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.view.endEditing(true)
if (searchBar.text?.count)! > 0 {
searchHandler(searchText: searchBar.text!)
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
searchBar.showsCancelButton = false
self.view.endEditing(true)
filteredValues?.removeAll() // this removes any previous array items
filteredValues = listValues // this assigns your listValues to filteredValues
collectionView?.reloadData() // this reloads your collectionView
}
func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (searchBar.text?.count)! > 0 {
searchHandler(searchText: searchBar.text!)
}
return true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchHandler(searchText: searchText)
}
fileprivate func searchHandler(searchText: String) {
//implement your filtering here
}
}
Again, there are different ways you can implement your search filtering and assign your filtered values to the collectionView data source.
Hope this helps. Thanks

Related

Why I can't get the results out of my textDidChange method?

edit: I solved the problem by uncommenting searchBar delegate in viewDidLoad. Thank you
I'm working on a project on using realm. But my problem is when i search the items with this code below it doesn't make any filter and all i see is all the items not the ones i search.
func loadItems() {
todoItems = selectedCategory?.items.sorted(byKeyPath: "title", ascending: true)
tableView.reloadData()
}
}
//MARK: - Search Bar Methods
extension ToDoListViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == "" {
loadItems()
DispatchQueue.main.async {
searchBar.resignFirstResponder()
}
}else{
todoItems = todoItems?.filter("title CONTAINS[cd] %#", searchBar.text!).sorted(byKeyPath: "dateCreated", ascending: true)
tableView.reloadData()
}
}
}

Why is my searchBar not resetting to the initial state after the cancel button is clicked?

I have a searchBar with a cancel button. When I click on cancel button it doesn't reset the searchBar to its initial state.
Here is the full source code.
var searchBar: UISearchBar = UISearchBar()
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchBarText = searchBar.text?.lowercased()
searchBarScope = searchBar.selectedScopeButtonIndex
showList()
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = nil
searchBar.setShowsCancelButton(false, animated: true)
searchBar.endEditing(true)
}
public func setupSearchBarStyle() {
UISearchBar.appearance().searchBarStyle = .minimal
UISearchBar.appearance().backgroundColor = UIColor.white
UISearchBar.appearance().barTintColor = UIColor.white
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.searchBar.showsScopeBar = true
if (navigationItem.title != nil) {
self.searchBar.scopeButtonTitles = [String(format: "gesamte %#", ci("project_s")), String(format: "in %#", navigationItem.title!)]
}
}
override func viewDidLayoutSubviews() {
self.searchBar.sizeToFit()
}
public override func viewDidLoad() {
self.navigationController?.setNavigationBarHidden(false, animated: false)
navigationItem.title = navigationItem.title ?? ci("plan_p")
guard let projectId = GlobalState.selectedProjectId, let byProject : Results<Structure> = self.by(projectId: projectId) else {
return
}
//search bar
tableView.rowHeight = 100.0
tableView.tableHeaderView = searchBar
self.searchBar.showsCancelButton = true
self.searchBar.sizeToFit()
self.definesPresentationContext = true
self.searchBar.delegate = self
tableView.allowsMultipleSelectionDuringEditing = true
How can I change the searchBar to its initial state after the user clicks on the cancel button? Right now it changes the searchText to nil after the user clicks on cancel.
In the searchBarCancelButtonClicked func:
searchBar.text = ""
searchBar.showsCancelButton = false
Also in thetextDidChange :
yourSearchBar.showsCancelButton = true
I think its because of this code:
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
It has to be :
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
}

What is the method for the NSSearchField TextDidChange?

What is the analogous method for the function searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) in macOS?
Got the answer:
#IBOutlet weak var searchBar: NSSearchField!
func controlTextDidChange(_ obj: Notification){
let searchObject:NSSearchField? = obj.object as? NSSearchField
if searchObject==self.searchBar{
}
}
The equivalent is the delegate method controlTextDidChange:
The object of the notification is the NSSearchfield. You have to cast the type
#IBOutlet weak var searchBar: NSSearchField!
func controlTextDidChange(_ notification : Notification){
guard let field = notification.object as? NSSearchField, field == self.searchBar else { return }
}
You need to add the controlTextDidChange method as shown in the pic below(last method) then the searchFieldDidEndSearching
keeps track of when you finish searching or if searchbar is empty and the searchFieldDidStartSearching(_ sender: NSSearchField) gets called when you just start editing the textfield after being empty
DispatchQueue.main.async {
self.searchTable.reloadData()
}
}
func searchFieldDidStartSearching(_ sender: NSSearchField) {
}
func controlTextDidChange(_ obj: Notification) {
guard let field = obj.object as? NSSearchField, field == self.searchBar else { return }
filteredPokemonList = allPokemonList.filter({ (pokemon) -> Bool in
return pokemon.name.lowercased().contains(field.stringValue.lowercased())
})
DispatchQueue.main.async {
self.searchTable.reloadData()
}
}
below is a pic of my Attribute Inspector to have a function called based on each letter entered to filter and reload the NSTableView

want to create a search bar like google in swift

I have an array like ["apple","appear","Azhar","code","BCom"] etc. This array contain more than half a million of records.
Now what I want to do, is to place a UISearchBar like in google and then whenever user types a text, then the dropdown list would appear with all the results containing this text and user could select one from the list.
For example - if the user types "a", then "apple","appear" and "Azhar" would appear in a drop-down list.
I don't want to use a UITableView or anything else to load the records. Whenever user types any word it should collect records from the array and make a drop down to display them.
How can I do this?
Suggestions required please.
Pretty simple code that would do the trick, the search bar filter is easy, as for the drop down menu i use a third party Pod named 'DropDown' that is very easy to use : https://github.com/AssistoLab/DropDown
import UIKit
import DropDown
class ViewController: UIViewController, UISearchBarDelegate {
var data: [String] = ["apple","appear","Azhar","code","BCom"]
var dataFiltered: [String] = []
var dropButton = DropDown()
#IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
dataFiltered = data
dropButton.anchorView = searchBar
dropButton.bottomOffset = CGPoint(x: 0, y:(dropButton.anchorView?.plainView.bounds.height)!)
dropButton.backgroundColor = .white
dropButton.direction = .bottom
dropButton.selectionAction = { [unowned self] (index: Int, item: String) in
print("Selected item: \(item) at index: \(index)") //Selected item: code at index: 0
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
dataFiltered = searchText.isEmpty ? data : data.filter({ (dat) -> Bool in
dat.range(of: searchText, options: .caseInsensitive) != nil
})
dropButton.dataSource = dataFiltered
dropButton.show()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
for ob: UIView in ((searchBar.subviews[0] )).subviews {
if let z = ob as? UIButton {
let btn: UIButton = z
btn.setTitleColor(UIColor.white, for: .normal)
}
}
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.text = ""
dataFiltered = data
dropButton.hide()
}
}

How i use UISearchController in UICollectionViewController using Swift

I want to implement UISearchController in UICollectionViewController. But i don't want to implement search in CollectionView I need SearchController in Swift.
I need to show Search Controller on Search Click
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { }
func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) { }
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.view.addSubview(searchController.view)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { }
func updateSearchResultsForSearchController(searchController: UISearchController) {}
func updateSearchResults(for searchController: UISearchController) { }
I am adding when search is active but not showing
let searchController = UISearchController(searchResultsController: nil)
Please suggest me if any one have any idea .