Swift UIScrollView:键盘不会以交互方式解除

我想以交互方式关闭键盘,但我的代码无效。 我不知道为什么。 当我尝试键盘解除模式onDrag它工作正常,不需要任何更多的代码。 这是我的代码:

  import UIKit class LoginViewController: UIViewController, UITextFieldDelegate{ @IBOutlet weak var txtUserName: UITextField! @IBOutlet weak var txtPassword: UITextField! @IBOutlet weak var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = false; scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive // Do any additional setup after loading the view. } @IBAction func LoginTapped(sender: AnyObject) { //here my code which is running } func textFieldShouldReturn(textField: UITextField!) -> Bool { //delegate method textField.resignFirstResponder() return true } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive } } 

以下是模拟器的屏幕截图

在此处输入图像描述

请查看,如果可能,请告诉我错误的位置。

使用此代码。 当您点击屏幕上的任何位置时,这将结束编辑。

  override func viewDidLoad() { super.viewDidLoad() //Looks for single or multiple taps. var tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard") view.addGestureRecognizer(tap) } //Calls this function when the tap is recognized. func DismissKeyboard(){ //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } 

希望有所帮助。

我有同样的问题,我终于解决了!

对我来说,朱利安的解决方案没有奏效,所以我不得不这样做:

在Storyboard中设置TapGestureRecognizer,然后在ViewController中设置Outlet

 @IBOutlet var tapGesture: UITapGestureRecognizer! 

然后在ViewController中设置IBAction

 @IBAction func DismissKeyboard(sender: UITapGestureRecognizer) { self.view.endEditing(true) } 

将这些行添加到viewDidLoad方法中

 override func viewDidLoad() { super.viewDidLoad() self.view.addGestureRecognizer(tapGesture) } 

它应该工作

希望有所帮助!

下面的代码将适用于所有UITextField的UIView中的所有组件

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { for (UIView * txt in self.view.subviews){ if ([txt isKindOfClass:[UITextField class]] && [txt isFirstResponder]) { [txt resignFirstResponder]; } } }