Search code examples
iosswiftdelegatessearchbar

Swift: How use delegate


I have AllOrganizacionUIView class, I used UISearchBarDelegate delegate, on workink

class AllOrganizacionUIView: UIView , UISearchBarDelegate {

  @IBOutlet var SearchBar: UISearchBar!
  var searchActive : Bool = false

  func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchActive = true;
  }

  func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    searchActive = false;
  }

  func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
  }

  func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
    aa.SearchBar.endEditing(true)
    print("hajox")
  }
}

I Have use UISearchBarDelegate delegate in ViewController class,

 class ViewController: UIViewController{
   @IBOutlet var SearchBar: UISearchBar!
   // not working
   func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
     self.CircleImageView_3.image = UIImage(named: "FullCircle")
     self.CircleImageView_2.image = UIImage(named: "Circle")
     self.CircleImageView_1.image = UIImage(named: "Circle")
     self.mMainCategory.hidden = true
     self.mAllCategores.hidden = true
     self.mAllOrganizations.hidden = false
     self.FooterViewController.text = "Основные категории"

     return true
   }
}

Help me please with this problem.


Solution

  • You have to set delegate for your search bar, possibly in viewDidLoad():

    override func viewDidLoad() {
        super.viewDidLoad()
        self.SearchBar.delegate = self
    }
    

    But it will be much better if you point the delegate on storyboard instead of code.

    So, I see two problems in your code. First, you mean that your delegate is an UIView subclass. But then you mean that you want to use delegate which is implemented in UIViewController subclass.

    You're able to have only one delegate at the same time. Choose one (view controller is preferred), and implement all delegate methods there. Then just set delegate as I said at the beginning of my answer.

    Actually, I suggest you to read about protocols and delegates at the official Apple's documentation website. It is really necessary to read documentation carefully, because there are a lot of unique things in iOS that are different to another platforms.