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

时间:2015-05-25 08:53:10

标签: ios 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
        }
    }

以下是模拟器

的屏幕截图

enter image description here

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

3 个答案:

答案 0 :(得分:5)

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

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

希望有所帮助。

答案 1 :(得分:1)

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

对我而言,朱利安的解决方案没有奏效,所以我必须这样做:

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

它应该工作

希望这会有所帮助!

答案 2 :(得分:-2)

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

#stern