Swift UIScrollView:键盘不会以交互方式关闭

Swift UIScrollView : keyboard doesn't dismiss interactively

我想以交互方式关闭键盘,但我的代码不起作用。我不知道为什么。 当我尝试键盘关闭模式 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)
}

希望对您有所帮助。

下面的代码将适用于所有 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];
    }
  }
}

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

对我来说,朱利安的解决方案没有用,所以我不得不照原样去做:

在 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)
}

它应该有效

希望对您有所帮助!