2017-08-09 7 views
0

UITextViewをサブクラス化し、その内部にユーザー入力を処理したいと考えています。デリゲートを別のものに設定することが可能なはずなので、デリゲートを利用することは選択肢ではありません。誰でも私はこれをどのように達成できるのか知っていますか?UITextViewでユーザー入力を検出する(委任以外に)

答えて

1

これを回避する方法があります。 UITextViewTextDidChange通知を使用できます。

class UITextViewPlus: UITextView { 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     NotificationCenter.default.addObserver(self, selector: #selector(textChange(_:)), name: .UITextViewTextDidChange, object: nil) 
    } 

    func textChange(_ sender: NSNotification) { 
     guard let textView = sender.object as? UITextViewPlus, textView == self else { 
      // ignoring text change of any other UITextView 
      return 
     } 

     // do something 
    } 

    deinit { 
     NotificationCenter.default.removeObserver(self) 
    }  
} 

注:だけUITextViewTextDidChange通知がどのUITextViewで任意のテキストの変更のために掲載されて心に留めておきます。