I have a UITextView, user can write maximum 160 character in the textView. How can i fixed the maximum text length of a UITextView?
I have a UITextView, user can write maximum 160 character in the textView. How can i fixed the maximum text length of a UITextView?
Replace
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
with
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
which is answered here
Swift 4,
I have written an extension of UITextView in swift 4, for making the code reusable. Also works fine with copy paste.
private var maxLengths = [UITextView: Int]()
extension UITextView : UITextViewDelegate {
@IBInspectable var maxLength: Int {
get {
guard let length = maxLengths[self]
else {
return Int.max
}
return length
}
set {
maxLengths[self] = newValue
self.delegate = self
}
}
@objc func limitLength(textView: UITextView) {
guard let prospectiveText = textView.text,
prospectiveText.count > maxLength
else {
return
}
let selection = selectedTextRange
let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
text = String(prospectiveText[..<maxCharIndex])
selectedTextRange = selection
}
public func textViewDidChange(_ textView: UITextView) {
limitLength(textField:textView)
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
scrollToBottom()
return true
}
public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
scrollToBottom()
return true
}
func scrollToBottom() {
let location = text.count - 1
let bottom = NSMakeRange(location, 1)
self.scrollRangeToVisible(bottom)
}
}
Set max length value in storyboard,