How i use UISearchController in UICollectionViewController using Swift - 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 .

Related

How to make sure the SearchBar Textfield is empty

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

UISearchBar Cancel Button function not working

I want to do sth. each time the cancel button is tapped inside the searchBar.
It is not working and not even calling the searchBarCancelButtonClicked method.
https://i.stack.imgur.com/Iho1V.png
class TableViewController: UITableViewController, UISearchBarDelegate {
#IBOutlet weak var searchbar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
searchbar.delegate = self
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
print("Cancel Button Clicked")
}
}

UiSearchController to UiCollectionView in Swift

I want to add Search bar programmatically. I want it to look like in Settings App (appear when scrolling down and disappear when scrolling up).
But Search Bar doesn't appear.
Outline:
ViewController:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
var filtered:[String] = []
var searchActive : Bool = false
let searchController = UISearchController(searchResultsController: nil)
#IBOutlet weak var collectionView: UICollectionView!
var items = ["Apple", "Orange", "Apple", "Orange", "Apple", "Orange", "Apple", "Orange", "Apple", "Orange", "Apple", "Orange"]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
self.searchController.searchResultsUpdater = self
self.searchController.delegate = self
self.searchController.searchBar.delegate = self
self.searchController.hidesNavigationBarDuringPresentation = false
self.searchController.dimsBackgroundDuringPresentation = true
self.searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search..."
searchController.searchBar.sizeToFit()
searchController.searchBar.becomeFirstResponder()
self.navigationItem.titleView = searchController.searchBar
self.definesPresentationContext = true
self.searchController.searchBar.placeholder = "Search for Items"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if searchActive {
return filtered.count
}
else
{
return items.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.contentView.layer.cornerRadius = 7.0
cell.contentView.layer.borderWidth = 1.0
cell.contentView.layer.borderColor = UIColor.clear.cgColor
cell.contentView.layer.masksToBounds = false
cell.layer.cornerRadius = 7.0
return cell
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false
self.dismiss(animated: true, completion: nil)
}
func updateSearchResults(for searchController: UISearchController)
{
let searchString = searchController.searchBar.text
filtered = items.filter({ (item) -> Bool in
let countryText: NSString = item as NSString
return (countryText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound
})
collectionView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true
collectionView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchActive = false
collectionView.reloadData()
}
func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
if !searchActive {
searchActive = true
collectionView.reloadData()
}
searchController.searchBar.resignFirstResponder()
}
}
App is working, showing items, but there is no search bar while scrolling.
Maybe this is because I am using UiCollectionView instead of UiTableView and I have to add some additional code?
What am I missing?
Video, how it looks: https://drive.google.com/file/d/1P0carjjgiForBnK_UmiuBWWk5A7BqSWB/view?usp=sharing
Are you running in iOS 11? Did you pull down the collection view? the search bar only appears when pull down. The only difference that I see with one that I have working is this, the navigationItem searchcontroller:
self.navigationItem.searchcontroller = searchcontroller
Your code is not working because you don’t have a navigation controller. At least it doesn’t show in the code or in the video. If you don’t, you need to embed the viewController in a navigationController.

Deactivate UIRefreshControl while searching

I implemented a UIRefreshControl on a TableView and additionally, I added a searchController with a searchBar.
The search as well as the pull to refresh work perfectly fine, the only thing I'm struggling with is how to deactivate the "pull to refresh" function when the searchController is active.
I tried implementing this solution, but somehow that did not work for me.
Make your viewcontroller conform the UISearchBarDelegate
class ViewController: UIViewController, UISearchBarDelegate
and implement two of its methods
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.removeRefreshControl()
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
self.initRefreshControl()
}
In each method call the functions to set and remove the UIRefreshControl
func initRefreshControl() {
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: #selector(ViewController.refreshData), for: .valueChanged)
self.tableView.refreshControl = self.refreshControl
}
func removeRefreshControl() {
self.refreshControl = nil
}
The complete code is:
class ViewController: UIViewController, UISearchBarDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var searchBar: UISearchBar!
var refreshControl: UIRefreshControl?
override func viewDidLoad() {
super.viewDidLoad()
self.initRefreshControl()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.removeRefreshControl()
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
self.initRefreshControl()
}
func initRefreshControl() {
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: #selector(ViewController.refreshData), for: .valueChanged)
self.tableView.refreshControl = self.refreshControl
}
func removeRefreshControl() {
self.refreshControl = nil
}
#objc func refreshData() {
....
....
self.refreshControl?.endRefreshing()
}
}
This should work.

SearchResultsUpdating not updating

Ok so I have a UITableViewController and created a SearchViewController to search through an array of investments I made. The investments display in the UITableView (by alphabetical order), but when I click search and type in some letters, there in no updating to show investments with those letters.
I feel like this is a simple mistake I made and it would really help if I could get some tips and help.
Here are a couple images of the code I have right now. (Sorry if I included some unnecessary code)
and also this one:
Thanks guys and hope that it can be solved.
What i would recommend you to do is to implement the UISearchBarDelegate methods an there you can do search by word or when user types the search on the keyboard where you should filter the dataSource and then reset the tableview data (this will update your table with the new data the user is searching for)
In your implementation you did not added
searchbar.delegate = self
so the search doesn't know you are searching
EDIT: to implement UISearchBarDelegate to as follows
class NewTableViewController: UITableViewController {
ovveride viewDidLoad() {
super.viewDidLoad()
searchbar.delegate = self
}
}
extension NewTableViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
search()
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
search()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
search()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
search()
}
func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) {
search()
}
}