-1

I put a function in my code like this:

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

where textfield is connect to a UITextField item.

@IBOutlet weak var textfield: UITextField!

but when I run the program, actually I cannot hide it wherever I tap or click. Could you please help me to solve it?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
chucklai
  • 814
  • 2
  • 10
  • 26

2 Answers2

0

Need to set delegate

override func viewDidLoad() {
    super.viewDidLoad()
    textfield.delegate = self                  //set delegate 
}
KKRocks
  • 8,222
  • 1
  • 18
  • 84
  • Since there is an outlet, why do this in code? Connect the text field's delegate in the storyboard. – rmaddy May 09 '17 at 21:00
  • I added delegate setting. now I can dismiss keyboard by clicking on return button. if I want to dismiss it when I tap at anywhere on the screen. how and why ? thanks? – chucklai May 10 '17 at 08:03
  • try this : override func touchesBegan(touches: Set, withEvent event: UIEvent?) { self.view.endEditing(true) } – KKRocks May 10 '17 at 08:09
-2

add this delegate UITextFieldDelegate

Wasim Akram
  • 51
  • 2
  • 9