Swift UIScrollView: keyboard does not turn off interactively

I want to disable keyboard interactively, but my code is not working. I do not know why. When I try to disable keyboard mode onDrag

it works fine and no code is required to do this. 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

enter image description here

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

+3


source to share


3 answers


Use this code. This will stop editing when clicked 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 it helps.

+5


source


I had the same problem and finally solved it!

Julian's solution didn't work for me, so I had to do it as is:

Install TapGestureRecognizer in your storyboard and then exit to your ViewController

@IBOutlet var tapGesture: UITapGestureRecognizer!

      

Then set 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 his job should

Hope it helps!

+1


source


The following code will work with all components in a UIView for all UITextField

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

      

-1


source







All Articles