user3323303 user3323303 - 3 months ago 11
Swift Question

in swift how to dismiss the key board

I am wondering how to dismiss a key board if the user touches outside the

UITextField
. I am using Xcode 6.1. I added a
UITextField
to a
UIViewController
as per the below thru
ViewDidLoad()
function. Any help on dismissing the key board would be much appreciated.

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

}

Answer

You need to have a reference to the UITextField so make a property value like this

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

Then to dismiss the keyboard you resign its as the first responder.

self.textBox1.resignFirstResponder()

Update to dimiss keyboard

Dismissing on return/done with the textField delegate method

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

Dismissing on a button click (custom IBAction method)

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