在swift中如何解雇键盘

时间:2014-11-18 11:41:50

标签: swift keyboard uitextfield xcode6.1

我想知道如果用户在UITextField之外触摸,如何解除键盘。我正在使用Xcode 6.1。我根据下面的UITextField函数向UIViewController添加了ViewDidLoad()。任何解雇关键董事会的帮助都将不胜感激。

    class PickerdemoViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate{

var textBox1 : UITextField!

override func viewDidLoad() {

//..................adding text box.........................//

    self.textBox1 = UITextField (frame: CGRectMake(100, 152.5, 50, 35))
    textBox1.delegate = self
    textBox1.backgroundColor = UIColor.whiteColor()
    textBox1.placeholder = "enter"
    textBox1.keyboardType = UIKeyboardType.DecimalPad
    self.textBox1.resignFirstResponder()
    textBox1.keyboardAppearance = UIKeyboardAppearance.Default
    self.view.addSubview(textBox1)



    super.viewDidLoad()

}

2 个答案:

答案 0 :(得分:1)

您需要引用UITextField,因此请创建一个属性值

class MyClass: UIViewController {
  var textBox1: UITextField!
  ...
  // create your textfield where ever you were by assigning it to self.textBox1
}

然后关闭键盘,你将其作为第一响应者辞职。

self.textBox1.resignFirstResponder()

更新到dimiss键盘

使用textField委托方法退回/完成

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

点击按钮时解雇(自定义IBAction方法)

@IBAction func buttonClicked(sender: UIButton!) {
    self.textBox1.resignFirstResponder()
}

答案 1 :(得分:0)

这将通过点击屏幕来关闭键盘。确保不要将它放在viewDidLoad中。

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {  // this func lets you close keyboard by touching screen
    self.view.endEditing(true) // this line lets you close keyboard by touching screen
}