0

I'm trying to create a class which only purpose is to implement UITextViewDelegate, but for some reason the method shouldChangeTextInRange is never called, here is my code:

public class TTextViewDelegate: NSObject, UITextViewDelegate {

public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    print("!!!!!! Should change text in range: \(text)")

    return true
  }

}

And in my viewcontroller:

textView.delegate = TTextViewDelegate()

Why does UITextViewDelegate only work if it is implemented in a viewcontroller?

Lorenzo
  • 3,293
  • 4
  • 29
  • 56
user1354603
  • 4,034
  • 4
  • 31
  • 43
  • It will work. The problem is you are not holding the object of `TTextViewDelegate` class as a strong reference. Just keep it in some class variable and assign it to textView delegate. Thanks. – if-else-switch Oct 15 '15 at 08:42
  • Possible duplicate of [Swift reusable UITextFieldDelegate](http://stackoverflow.com/questions/33006082/swift-reusable-uitextfielddelegate) – t4nhpt Oct 15 '15 at 09:43

1 Answers1

0

public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

The text view calls this method whenever the user types a new character or deletes an existing character. Implementation of this method is optional. You can use this method to replace text before it is committed to the text view storage. For example, a spell checker might use this method to replace a misspelled word with the correct spelling.

range

The current selection range. If the length of the range is 0, range reflects the current insertion point. If the user presses the Delete key, the length of the range is 1 and an empty string object replaces that single character.

text

The text to insert.

vijay
  • 165
  • 1
  • 5
  • Thank you for your answer, however just posting information about the method is not what I asked for. The question was: Why cannot I implement UITextViewDelegate in a class which is not the viewcontroller? – user1354603 Oct 15 '15 at 08:39