简体   繁体   English

用swift编程语言隐藏文本字段的键盘

[英]hide keyboard for text field in swift programming language

I have little experience in Objective-C.我在Objective-C方面的经验很少。 I want to hide the keyboard for a text field using the Swift programming language.我想使用 Swift 编程语言隐藏文本字段的键盘。

I also tried this我也试过这个

func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
    return true;
}

But the method is not getting triggered when I hit return.但是当我点击返回时,该方法没有被触发。 Anyone have any luck with this?有没有人有这方面的运气?

I think the Problem is with setting the Delegate.我认为问题在于设置委托。

Please set textfield Delegate to your ViewController like this请像这样将 textfield Delegate 设置为您的 ViewController

class ViewController: UIViewController,UITextFieldDelegate {

and then create the IBOutlet for your text field like this然后像这样为您的文本字段创建 IBOutlet

@IBOutlet var txtTest : UITextField = nil

make sure that it is connected to your text field on your view in storyboard.确保它已连接到情节提要中视图上的文本字段。

finally set its Delegate using最后使用

txtTest.delegate=self

We are almost done.我们快完成了。 Now place this delegate function into your class.现在将此委托函数放入您的类中。

func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
    {
        textField.resignFirstResponder()
        return true;
    }

Hope this will solve your issue.希望这能解决您的问题。

Just override the UIViewController method called "touchesBegan" and set endEditing to true.只需覆盖名为“touchesBegan”的 UIViewController 方法并将 endEditing 设置为 true。 Just like this:像这样:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
    self.view.endEditing(true)
}

In order to hide the keyboard when you pressed a button, you need to use the following function.为了在按下按钮时隐藏键盘,您需要使用以下功能。

self.view.endEditing(true)

This works when a button is pressed.这在按下按钮时起作用。

Hope this helps someone out there.希望这可以帮助那里的人。

Here we go:开始了:

  1. Add a textField to your View将 textField 添加到您的视图
  2. Create a new Swift file创建一个新的 Swift 文件
  3. Set this new file as a Class for that particular View将此新文件设置为该特定视图的类
  4. Add a TextField to your View将 TextField 添加到您的视图
  5. Create an Outlet for the textfield (my is named "txtField" !)为文本字段创建一个出口(我的名为“txtField”!)
  6. Substitute any code in the Swift Class file with this:将 Swift 类文件中的任何代码替换为:

     import Foundation import UIKit //01 create delegation class MyViewController2: UIViewController,UITextFieldDelegate { @IBOutlet weak var txtField: UITextField!=nil override func viewDidLoad() { super.viewDidLoad() // additional setup after loading the view //02 set delegate to textfield txtField.delegate = self } //03 textfield func for the return key func textFieldShouldReturn(textField: UITextField) -> Bool { txtField.resignFirstResponder() return true; } //textfield func for the touch on BG override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { txtField.resignFirstResponder() self.view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() //dispose of any resources that can be recreated } }
    1. Try it out, be happy & say thanks !试试看,开心并说声谢谢!

Now In Swift 3/4/5, the easiest methods are现在在 Swift 3/4/5 中,最简单的方法是

Method 1: called when 'return' key pressed.方法 1:在按下 'return' 键时调用。

func textFieldShouldReturn(_ textField: UITextField) -> Bool 
 {
 textField1.resignFirstResponder()
 textField2.resignFirstResponder()
        return true;
    }

Method 2: called when 'return' key pressed.方法 2:在按下 'return' 键时调用。

func textFieldShouldReturn(_ textField: UITextField) -> Bool 
    {
    self.view.endEditing(true)
        return true;
    }

Method 3: Global Method Write in view did load方法 3:全局方法写入视图确实加载

self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))

Note: Don't forget to add this.注意:不要忘记添加这个。 Other wise its not work.否则它不起作用。

UIGestureRecognizerDelegate, UITextFieldDelegate

I hope it will work for you :)我希望它对你有用:)

In simple way to hide the keyboard just override the UIView "touchBegan method".以简单的方式隐藏键盘只需覆盖 UIView“touchBegan 方法”。 So when you tap any where in the view keyboard is hide.因此,当您点击视图中键盘隐藏的任何位置时。 here is the sample code.. (Swift 3.0 Updated code)这是示例代码..(Swift 3.0 更新代码)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
{
   self.view.endEditing(true)
}

Like @spfursich said, The best way is, when user touch anywhere above the keyboard the keyboard will disappear.就像@spfursich 所说的那样,最好的方法是,当用户触摸键盘上方的任何位置时,键盘就会消失。 Here is the code :这是代码:

override func viewDidLoad() {
    super.viewDidLoad()

    var tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
    self.view.addGestureRecognizer(tap)
}

func DismissKeyboard(){
    self.view.endEditing(true)
}
  • Add UITextFieldDelegate to the class declaration:将 UITextFieldDelegate 添加到类声明中:

    class ViewController: UIViewController, UITextFieldDelegate类 ViewController: UIViewController, UITextFieldDelegate

  • Connect the textfield or write it programmatically连接文本字段或以编程方式编写

    @IBOutlet weak var userText: UITextField! @IBOutlet 弱变量 userText:UITextField!

  • set your view controller as the text fields delegate in view did load:将您的视图控制器设置为视图中的文本字段委托加载:

     override func viewDidLoad() { super.viewDidLoad() self.userText.delegate = self }
  • Add the following function添加以下功能

    func textFieldShouldReturn(userText: UITextField!) -> Bool { userText.resignFirstResponder() return true; }

    with all this your keyboard will begin to dismiss by touching outside the textfield aswell as by pressing return key.有了所有这些,您的键盘将通过触摸文本字段外部以及按返回键开始关闭。

UIApplication.sharedApplication().sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, forEvent:nil)

First you need to set delegate for your textfield then you need to include resignFirstResponder() to hide keyboard when press return button of keybaord.首先,您需要为文本字段设置delegate ,然后您需要包含resignFirstResponder()以在按下键盘的返回按钮时隐藏键盘。

 func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
 {
   textField .resignFirstResponder()
   return true;
 }

You can try this code to have the "return" key execute code.您可以尝试使用此代码让“返回”键执行代码。

func textFieldShouldReturn(textField: UITextField) -> Bool{
    textField.resignFirstResponder()
    performAction()
    return true;
}

func performAction(){

//execute code for your action inside this function

}

Hope this can help you.希望这可以帮到你。

You can also do like this: add event "Did end on exit" from connections inspector of your TextField and connect it to method from relevant ViewController您也可以这样做:从 TextField 的连接检查器添加事件“Did end on exit”,并将其连接到相关 ViewController 的方法

In my example I connect it to method called 'ended'在我的示例中,我将其连接到名为“已结束”的方法

declare sender as UITextField and then call sender.resignFirstResponder();将 sender 声明为 UITextField,然后调用 sender.resignFirstResponder(); Like this:像这样:

@IBAction func ended (sender: UITextField){ sender.resignFirstResponder(); }

Here i have solved the problem, that when keypad opens and the view gets hidden behind the keypad .... that time we need to change the UI constraints dynamically in order to make the whole view visible.在这里我已经解决了这个问题,当键盘打开并且视图隐藏在键盘后面时......那个时候我们需要动态更改 UI 约束以使整个视图可见。 In my case i am changing the bottonConstraint of the UITextField dynamically.就我而言,我正在动态更改UITextField的 bottonConstraint。

So, here goes the complete code.所以,这里是完整的代码。 I have one UITextView and UITextField on UIViewController to work on for just testing...我在UIViewController上有一个UITextViewUITextField用于测试...

import UIKit

class ViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate {

    @IBOutlet weak var textView: UITextField!

    @IBOutlet weak var textField: UITextView!

      /*Height Constraint for textField*/
    @IBOutlet weak var bottom: NSLayoutConstraint!

    var defaultHeight:CGFloat = 0.0;

    override func viewDidLoad() {
        super.viewDidLoad()

        defaultHeight = bottom.constant;

        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);


        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);

    }

    override func resignFirstResponder() -> Bool {
        textView.resignFirstResponder();
        textField.resignFirstResponder();
        return true;
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        resignFirstResponder()
        print("touched began")
    }

    func textViewDidEndEditing(textView: UITextView) {
        resignFirstResponder()
        print("text view did end editing")
    }

    func textViewShouldEndEditing(textView: UITextView) -> Bool {
        resignFirstResponder()
        print("text view should end editing")
        return true;
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        print("text field should return")
        resignFirstResponder()
        return true;
    }

    func textFieldDidEndEditing(textField: UITextField) {
        resignFirstResponder()
        print("did end editing")
    }

    func keyboardWillShow(notification: NSNotification) {
        print("keyboard will show.............")
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            let a = keyboardSize.height;
            self.bottom.constant = a + defaultHeight;
            self.view.updateConstraints();
        }
    }

    func keyboardWillHide(nofication:NSNotification)
    {
        print("keyboard will hide................")
        bottom.constant = defaultHeight;
        self.view.updateConstraints();

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

when you call your UIAlertController, place condition in the completion handler if you'd like to hide the keyboard.当您调用 UIAlertController 时,如果您想隐藏键盘,请在完成处理程序中放置条件。

self.present('nameOfYourUIAlertController', animated: true, completion: {
    if condition == true {
        'nameOfYourUIAlertController'.textFields![0].resignFirstResponder()
    }
})

This works great for me.这对我很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM