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

时间:2014-07-23 11:13:42

标签: ios swift uitextfield

我对Objective-C的经验不多。我想使用Swift编程语言隐藏文本字段的键盘。

我也试过这个

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

但是当我点击返回时,该方法没有被触发。有人有运气吗?

13 个答案:

答案 0 :(得分:69)

我认为问题在于设置代表。

请将textfield Delegate设置为您的ViewController,如下所示

class ViewController: UIViewController,UITextFieldDelegate {

然后为您的文本字段创建IBOutlet,如下所示

@IBOutlet var txtTest : UITextField = nil

确保它已连接到故事板中视图上的文本字段。

最后使用

设置其委托
txtTest.delegate=self

我们差不多完成了。现在将此委托功能放入您的班级。

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

希望这能解决您的问题。

答案 1 :(得分:9)

只需覆盖名为" touchesBegan"的UIViewController方法。并将endEditing设置为true。就像这样:

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

答案 2 :(得分:8)

为了在按下按钮时隐藏键盘,您需要使用以下功能。

self.view.endEditing(true)

按下按钮时有效。

希望这有助于那里的人。

答案 3 :(得分:6)

我们走了:

  1. 将textField添加到您的视图
  2. 创建一个新的Swift文件
  3. 将此新文件设置为该特定视图的类
  4. 将TextField添加到您的视图
  5. 为文本字段创建一个插座(我的名字叫“txtField”!)
  6. 用以下代码替换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. 试试看,快乐&说谢谢!

答案 4 :(得分:2)

  • 将UITextFieldDelegate添加到类声明:

    类ViewController:UIViewController,UITextFieldDelegate

  • 连接文本字段或以编程方式编写

    @IBOutlet weak var userText:UITextField!

  • 将视图控制器设置为视图中的委托文本字段加载:

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

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

    所有这些键盘将通过触摸文本区域以及按返回键开始解除。

答案 5 :(得分:1)

像@spfursich所说,最好的方法是,当用户触摸键盘上方的任何地方时,键盘将消失。这是代码:

override func viewDidLoad() {
    super.viewDidLoad()

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

func DismissKeyboard(){
    self.view.endEditing(true)
}

答案 6 :(得分:1)

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

答案 7 :(得分:1)

隐藏键盘的简单方法就是覆盖UIView" touchBegan方法"。因此,当您点击视图键盘中的任何位置时,隐藏。 这是示例代码..(Swift 3.0更新代码)

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

答案 8 :(得分:0)

首先,你需要为你的文本字段设置delegate,然后你需要包含resignFirstResponder()来按键盘按键的时候隐藏键盘。

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

答案 9 :(得分:0)

您可以尝试使用此代码使“返回”键执行代码。

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

func performAction(){

//execute code for your action inside this function

}

希望这可以帮到你。

答案 10 :(得分:0)

我已经解决了这个问题,当键盘打开并且视图隐藏在键盘后面 .... 那时我们需要动态更改UI约束为了使整个视图可见。在我的情况下,我正在动态地更改UITextField的bottonConstraint。

所以,这里是完整的代码。我在UITextView上有一个UITextFieldUIViewController来处理测试...

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

答案 11 :(得分:0)

现在在Swift 3中,最简单的方法是

方法1:在按下“返回”键时调用。

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

方法2:在按下“返回”键时调用。

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

方法3:全局方法在视图中写入加载

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

注意:不要忘记添加此内容。其他明智的不行。

UIGestureRecognizerDelegate, UITextFieldDelegate

我希望它对您有用:)

答案 12 :(得分:0)

在调用UIAlertController时,如果您想隐藏键盘,请在完成处理程序中放置条件。

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

这对我来说很好。