swift 中的异步任务后键盘未关闭

keyboard does not dismiss after async task in swift

我正在使用 UItextField 执行搜索任务,我点击搜索按钮它应该开始调用网络的异步任务 api 并且关闭键盘。但键盘仍然存在。这是代码

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

   attemptPost { (success) in
       DispatchQueue.main.async {
        spinner.stopAnimation(self)
        btnOk.isEnabled = true
        btnCancel.isEnabled = true
    }

     // after this keyboard should dismiss but does not do so
      return true
}

func attemptPost(_ completion:@escaping (Bool)->()) {
    // some code
}

我希望键盘在我们点击搜索按钮后关闭,异步任务也应该开始。

你必须辞去第一响应者。

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

   attemptPost { (success) in
       DispatchQueue.main.async {
        spinner.stopAnimation(self)
        btnOk.isEnabled = true
        btnCancel.isEnabled = true
    }

   textField.resignFirstResponder()
      return true
}

请参阅 https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619603-textfieldshouldreturn

上的讨论