Cohars
Cohars

Reputation: 4032

UITextView becomeFirstResponder() adds new line

I'm quite new to iOS/Swift and I have a strange behaviour when setting a UITextView as a first responder (when touching next from the previous UITextField). It automatically inserts a new line in the UITextView. The code:

class MyViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate {
  @IBOutlet weak var nameTextField: UITextField!
  @IBOutlet weak var descriptionTextView: UITextView!

  override func viewDidLoad() {
    nameTextField.delegate = self
    descriptionTextView.delegate = self
  }

  func textFieldShouldReturn(nameTextField: UITextField) -> Bool {
    nameTextField.resignFirstResponder()
    descriptionTextView.becomeFirstResponder()
    return true
  }

  func textView(descriptionTextView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if (text == "\n") {
      descriptionTextView.resignFirstResponder()
      return false
    }
    return true
  }
}

A new line is always added and i press next, even if there's already text or a new line. On the first next here is what happens (the cursor is automatically on the 2nd line). enter image description here

If I go back to the text field and press next again, the cursor is on the 3rd line). enter image description here

Upvotes: 3

Views: 2562

Answers (1)

Leo
Leo

Reputation: 24714

Return false in textFieldShouldReturn

func textFieldShouldReturn(nameTextField: UITextField) -> Bool {
    nameTextField.resignFirstResponder()
    descriptionTextView.becomeFirstResponder()
    return false
}

More details here

Upvotes: 10

Related Questions