1

The following triggers when the Done button is clicked on the keyboard. It goes into the conditional and returns false. However, the keyboard remains on the screen.

class MyViewController: UIViewController, UITextViewDelegate{


func textView(textView: UITextView!, shouldChangeTextInRange: NSRange, replacementText: NSString!) -> Bool {
    if(replacementText.isEqualToString("\n")) {
        textBox.resignFirstResponder()
        return false
    }
    return true
}

textBox is a delegate for the view. I have connected this through Interface Builder. Any ideas why it isn't dismissing the keyboard?

swiftBoy
  • 35,607
  • 26
  • 136
  • 135
4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • Have you set the delegate of the textbox to self? – Christian Mar 18 '15 at 15:49
  • At the bottom of the OP, I mention it is connected through IB. I even added textBox.delegate = self in viewDidLoad() but still nothing. – 4thSpace Mar 18 '15 at 15:49
  • @4thSpace try to change textBox to `textView.resignFirstResponder()`, see if it works – IxPaka Mar 18 '15 at 15:51
  • Use the textView that is passed in the delegate method instead of your property textBox. – Arbitur Mar 18 '15 at 15:51
  • Ah I missunderstood you. Do you have any other delegate methods like `textViewShouldEndEditing` in use which could stop the resignfirstresponder to work? Also have you tried using textView, the parameter of the delegate instead of your textBox? – Christian Mar 18 '15 at 15:52
  • Perfect! It should have been the passed in textView. Can one of you post as answer? – 4thSpace Mar 18 '15 at 15:57
  • possible duplicate of [Dismiss keyboard for UITextView without using Return key](http://stackoverflow.com/questions/10057242/dismiss-keyboard-for-uitextview-without-using-return-key) – sylvanaar Mar 18 '15 at 18:06

1 Answers1

0

First of all please ensure that your My ViewController is a delegate of the textField, And then, on the method shouldChangeTextInRange use the textView that is passed in the delegate method instead of your property textBox.

For example:

class MyViewController: UIViewController, UITextViewDelegate{

    func viewDidLoad(){
      super.viewDidLoad()
      textBox.delegate = self
    }

func textView(textView: UITextView!, shouldChangeTextInRange: NSRange, replacementText: NSString!) -> Bool {
    if(replacementText.isEqualToString("\n")) {
        textView.resignFirstResponder()
        return false
    }
    return true
}
swiftBoy
  • 35,607
  • 26
  • 136
  • 135
Guy Kahlon
  • 4,510
  • 4
  • 30
  • 41