IOS UISearch bar with keyboard actions in swift 4

IOS UISearch bar with keyboard actions in swift 4

1 .Fist Create a ViewController and extends UISearchbarDelegate

SearchViewController: UIViewController, UISearchBarDelegate{}

2 . Register search bar as like in ViewDidLoad

self.searchBar.delegate = self

3. Now call keyboard search action func

 func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
         print(searchBar.text)
 }

4 . Cancel button function

 func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
        searchBar.resignFirstResponder()
  
}

Complete Code


import UIKit

class SearchViewController: UIViewController ,UISearchBarDelegate{

    lazy var searchBar = UISearchBar(frame: CGRect.zero)

   override func viewDidLoad() {
        super.viewDidLoad()

        searchBar.placeholder = "Search"
        navigationItem.titleView = searchBar
        searchBar.text = "this"
        
 
        self.searchBar.delegate = self
        
   
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
        
    }
    

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
        searchBar.resignFirstResponder()
        print("cancel")
    }
   
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
         print(searchBar.text)
    }
   
}

Leave a Reply

Your email address will not be published. Required fields are marked *