3

I have the following code to limit the number of lines in UITextView

textView.textContainer.maximumNumberOfLines = 10
textView.textContainer.lineBreakMode = .byTruncatingTail

but is there a way to limit the number of characters of each line? how can i set the limit to 50 chars for each line?

EDIT: I tried the solution proposed as possible duplicate but the limit is applied over the entire text, I need to set the limit for each line.

Mono.WTF
  • 1,587
  • 3
  • 18
  • 28
  • 1
    Possible duplicate of [Setting maximum number of characters of \`UITextView \` and \`UITextField \`](http://stackoverflow.com/questions/32935528/setting-maximum-number-of-characters-of-uitextview-and-uitextfield) – l'L'l Jan 18 '17 at 00:08
  • @l'L'l No, I tried this solution but the limits is applied over the entire text, I need to set the limit for each line. – Mono.WTF Jan 18 '17 at 00:14
  • Alright, vote to close retracted. – l'L'l Jan 18 '17 at 00:15

1 Answers1

5

Implement shouldChangeTextIn and return false if any line has more than the allowed number of characters:

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let maxAllowedCharactersPerLine = 10
        let lines = (textView.text as NSString).replacingCharacters(in: range, with: text).components(separatedBy: .newlines)
        for line in lines {
            if line.characters.count > maxAllowedCharactersPerLine {
                return false
            }
        }
        return true
    }
Josh Homann
  • 15,933
  • 3
  • 30
  • 33