senty
senty

Reputation: 12847

Dismissing Keyboard on Custom UITextField

I am using TextFieldEffects for custom UITextFields. Creating the textfield was pretty straight forward..

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
        let textField = HoshiTextField(frame: textFieldFrame)
        textField.placeholderColor = .darkGrayColor()
        textField.foregroundColor = .lightGrayColor()

        view.addSubView(textField) 
   }
}

For dismissing the keyboard, I tried to do what I usually do, but unfortunately no luck.

func textFieldShouldReturn(textField: HoshiTextField) -> Bool {
    self.view.endEditing(true)
    return false
}

func dismissKeyboard() {
    view.endEditing(true)
}

Do you have any suggestions?

Upvotes: 0

Views: 733

Answers (3)

Muzahid
Muzahid

Reputation: 5186

Confirm the UITextFieldDelegate protocol to your ViewController and assign textField.delegate = self and then implement the following delegate method:

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

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

For better understanding please see my code snipetenter image description here

Upvotes: 2

tuledev
tuledev

Reputation: 10317

class ViewController: UIViewController, UITextFieldDelegate //add this protocol 
{
...
  func ... {
    let textField = HoshiTextField(frame: textFieldFrame)
    textField.placeholderColor = .darkGrayColor()
    textField.foregroundColor = .lightGrayColor()
    textField.delegate = self
  }
}

Upvotes: 1

Nhat Dinh
Nhat Dinh

Reputation: 3447

Set delegate for your textField and maybe it will work!

Upvotes: 0

Related Questions