how text length of a UITextView can be fixed?
Asked Answered
A

5

25

I have a UITextView, user can write maximum 160 character in the textView. How can i fixed the maximum text length of a UITextView?

Aiguille answered 6/1, 2010 at 10:22 Comment(1)
This is NOT a duplicate.... The user needs a method for determining the length of a UITextView not a UITextFieldHomely
M
15

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

Micromillimeter answered 6/1, 2010 at 11:53 Comment(0)
T
57

This chunk of code also works with Copy/Paste, but also copes with situation when trying to paste number of characters that will make the text view exceed the limit. In that case, only first characters of the string are pasted.

#define MAX_LENGTH 15 // Whatever your limit is
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSUInteger newLength = (textView.text.length - range.length) + text.length;
    if(newLength <= MAX_LENGTH)
    {
        return YES;
    } else {
        NSUInteger emptySpace = MAX_LENGTH - (textView.text.length - range.length);
        textView.text = [[[textView.text substringToIndex:range.location] 
                                            stringByAppendingString:[text substringToIndex:emptySpace]]
                                         stringByAppendingString:[textView.text substringFromIndex:(range.location + range.length)]];
        return NO;
    }
}
Thresathresh answered 5/5, 2011 at 12:48 Comment(3)
The only problem (unless it's just my implementation) is how to get a counter to work with this.Sickroom
What do you mean by 'counter'? Displaying number of characters in the text view? If yes, you can update the counter in textView:textDidChange: method (it works in my project).Thresathresh
NSUInteger emptySpace = MIN(0, MAX_LENGTH - (textView.text.length - range.length)); is better if you may have existing text which is longer then the allowed maximum.Interpretative
M
15

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

Micromillimeter answered 6/1, 2010 at 11:53 Comment(0)
L
13

Coming late to this answer; manicaesar's solution didn't work for me. Here's my implementation of the same idea:

#define MAX_LENGTH 140
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)replacementText
{
    NSString *newText = [ textView.text stringByReplacingCharactersInRange: range withString: replacementText ];
    if( [newText length]<= MAX_LENGTH ){
        return YES;
    }
    // case where text length > MAX_LENGTH
    textView.text = [ newText substringToIndex: MAX_LENGTH ];
    return NO;
}
Lioness answered 28/2, 2014 at 20:25 Comment(2)
I prefer this method since it also limits the characters when pasting a text that exceeds MAX_LENGTH. Mind you, replace the 'replacementText' with 'text' to avoid errors.Brasher
this is perfect, does not crashChrysoberyl
Z
1

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,

enter image description here

Zealotry answered 18/6, 2018 at 11:17 Comment(0)
F
0

Swift

fileprivate let maxLen = 5

    extension MyViewController : UITextViewDelegate{
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            
            let newLen = (textView.text.count - range.length) + text.count
            return newLen <= maxLen
        }
        
    }
Fotinas answered 6/9, 2017 at 13:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.