Created
November 27, 2017 21:49
-
-
Save azamsharp/3701c6852437d6005d7bdc7d09ccbf1c to your computer and use it in GitHub Desktop.
BindingTextView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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