在swift中禁用委托

时间:2018-01-20 13:39:49

标签: swift delegates google-places-api

我目前有一个名为searchTextField的文字字段。我还有两个名为firstButtonsecondButton的按钮。当我点击firstButton时,我会通过添加相关代理searchTextField.delegate=self在操作方法中启用Google Places API。

但是,当我点击secondButton时,我希望Google Places API被禁用,而这只是一个普通的文本字段。有没有办法禁用委托或其他方式来实现相同的结果?

@IBAction func firstAction(_ sender: Any) {
    searchTextField.delegate=self //google autocomplete
}

@IBAction func secondAction(_ sender: Any) {
    searchTextField.placeholder = "Search without Google API"
}

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    let autoCompleteController = GMSAutocompleteViewController()
    autoCompleteController.delegate = self

    let filter = GMSAutocompleteFilter()
    filter.type = .establishment
    autoCompleteController.autocompleteFilter = filter

    self.present(autoCompleteController, animated: true, completion: nil)
    return false
}

1 个答案:

答案 0 :(得分:0)

我想我会以不同的方式做到这一点

var googleAPIEnable = false
func viewDidLoad() {
  searchTextField.delegate = self
}

@IBAction func firstAction(_ sender: Any) {
  googleAPIEnable = false
}

@IBAction func secondAction(_ sender: Any) {
  searchTextField.text = nil
  searchTextField.placeholder = "Search without Google API"
  googleAPIEnabled = true
}

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
  guard googleAPIEnabled else {
    return true
  }

  let autoCompleteController = GMSAutocompleteViewController()
  autoCompleteController.delegate = self

  let filter = GMSAutocompleteFilter()
  filter.type = .establishment
  autoCompleteController.autocompleteFilter = filter

  self.present(autoCompleteController, animated: true, completion: nil)
  return false
}