Swift UIScrollView : keyboard doesn't dismiss

2019-05-03 23:18发布

问题:

I want to dismiss the keyboard interactively, but my code is not working. I don't know why. When I try the keyboard dismiss mode onDrag it is working fine and there is no need of any more code for that. Here is my code :

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

Here are screenshots of the simulator

Please take a look and if possible let me know where the error is.

回答1:

Use this code. This will end editing when you tap anywhere on the screen.

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

Hope that helps.



回答2:

I had the same problem and i finally solved it !

For me the Julian's solution didn't worked so i had to do it as it is :

Set a TapGestureRecognizer in your Storyboard and then an Outlet in your ViewController

@IBOutlet var tapGesture: UITapGestureRecognizer!

Then set an IBAction in your ViewController

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

add these lines to your viewDidLoad method

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

and its should work

Hope that will help !



回答3:

The below code will work on all the components in the UIView for all the UITextField

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