Search code examples
swiftswift2uikeyboardresignfirstresponder

How to hide keyboard in Custom UIView?


I have UIViewController(FirtViewController) in my Storyboard... In Swift file assigned to this UIViewController i add custom UIView

let customView = NSBundle.mainBundle().loadNibNamed("CustomView", owner: self, options: nil)[0] as! CustomView
self.view.addSubview(customView)

In this customView i have a textField. In swift file assigned to this customView i have function:

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

But when i pressed "return key" my keyboard don't hide!

Where is my mistake?


Solution

  • Wherever you added customView:

    customView.textField.delegate = self
    

    Next, on the line of FirstViewController's declaration, add conformance to UITextFieldDelegate.

    Then, put the textFieldShouldReturn: in the view controller.