Magesh
Magesh

Reputation: 277

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

}

Upvotes: 1

Views: 503

Answers (2)

Jevon Charles
Jevon Charles

Reputation: 684

This will dismiss the keyboard by tapping screen. Make sure to not put it in the 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
}

Upvotes: 0

sbarow
sbarow

Reputation: 2819

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

Upvotes: 1

Related Questions