Search code examples
iosswiftuisearchbaruisearchbardelegate

Is it possible to have UISearchBarDelegate extension in separate file?


extension HomeViewController: UISearchBarDelegate {


    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        //code
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
         //code     
    }
}

This was working fine when it was at the bottom of my HomeViewController.
I wonder if I can separate this extension in separate file?


Solution

  • I forgot to include UIKit.

    import Foundation
    import UIKit
    
    extension HomeViewController {
        func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)        {
          //code
        }
    
        func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
         //code
        } 
    }
    

    Also, you need to inherit UISearchBarDelegate in ViewController, not in extension.