Skip to content

Instantly share code, notes, and snippets.

@azamsharp
Created November 27, 2017 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azamsharp/3701c6852437d6005d7bdc7d09ccbf1c to your computer and use it in GitHub Desktop.
Save azamsharp/3701c6852437d6005d7bdc7d09ccbf1c to your computer and use it in GitHub Desktop.
BindingTextView
class BindingTextView : UITextView, UITextViewDelegate {
var numberOfCharactersEntered :(Int,Int) -> () = { _,_ in }
var limit :Int = 0
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.delegate = self
}
func bind(callback: @escaping (Int,Int) -> ()) -> BindingTextView {
self.numberOfCharactersEntered = callback
return self
}
func limit(to limit:Int) {
self.limit = limit
}
func textViewDidChange(_ textView: UITextView) {
self.numberOfCharactersEntered(self.text.count,self.limit)
}
func textView(_ textView: UITextView,
shouldChangeTextIn range: NSRange,
replacementText text: String) -> Bool {
let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
return newText.count <= self.limit
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment