使用Swift触摸任意位置以关闭iOS键盘

我一直在寻找这个,但似乎找不到。我知道如何使用来关闭键盘,Objective-C但是我不知道如何使用Swift?有人知道吗?



慕田峪7331174
浏览 835回答 3
3回答

Smart猫小萌

有关以下有关如何使用Swift在Xcode 6.1中关闭键盘的问题的答案:import UIKitclass ItemViewController: UIViewController, UITextFieldDelegate {&nbsp; &nbsp; @IBOutlet var textFieldItemName: UITextField!&nbsp; &nbsp; @IBOutlet var textFieldQt: UITextField!&nbsp; &nbsp; @IBOutlet var textFieldMoreInfo: UITextField!&nbsp; &nbsp; override func viewDidLoad() {&nbsp; &nbsp; &nbsp; &nbsp; super.viewDidLoad()&nbsp; &nbsp; &nbsp; &nbsp; textFieldItemName.delegate = self&nbsp; &nbsp; &nbsp; &nbsp; textFieldQt.delegate = self&nbsp; &nbsp; &nbsp; &nbsp; textFieldMoreInfo.delegate = self&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Called when 'return' key pressed. return NO to ignore.&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; func textFieldShouldReturn(textField: UITextField) -> Bool {&nbsp; &nbsp; &nbsp; &nbsp; textField.resignFirstResponder()&nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; }&nbsp; &nbsp;/**&nbsp; &nbsp; * Called when the user click on the view (outside the UITextField).&nbsp; &nbsp; */&nbsp; &nbsp; override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {&nbsp; &nbsp; &nbsp; &nbsp; self.view.endEditing(true)&nbsp; &nbsp; }}

慕运维8079593

Swift 4工作如下创建扩展名并hideKeyboardWhenTappedAround()在Base视图控制器中调用。////&nbsp; UIViewController+Extension.swift//&nbsp; Project Name////&nbsp; Created by ABC on 2/3/18.//&nbsp; Copyright © 2018 ABC. All rights reserved.//import UIKitextension UIViewController {&nbsp; &nbsp; func hideKeyboardWhenTappedAround() {&nbsp; &nbsp; &nbsp; &nbsp; let tapGesture = UITapGestureRecognizer(target: self,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;action: #selector(hideKeyboard))&nbsp; &nbsp; &nbsp; &nbsp; view.addGestureRecognizer(tapGesture)&nbsp; &nbsp; }&nbsp; &nbsp; @objc func hideKeyboard() {&nbsp; &nbsp; &nbsp; &nbsp; view.endEditing(true)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP