'UITextView - limit amount of characters per line

I have a UITextView and I want to line break each time a user is extending a limit of chars per line (let's say 30 chars per line is the maximum). And I want to save the word wrapping too so if a 30 limit is reached in the middle of a word, it should just go straight to the new line.

How should I approach this problem? I was hoping for a native solution but can't find anything related in the documentation.



Solution 1:[1]

You can use this workaround by using textViewDidChange delegate method from UITextViewDelegate to add newline after every 30 characters, like this

func textViewDidChange(_ textView: UITextView) {
    if let text = textView.text {
        let strings = string.components(withMaxLength: 30) // generating an array of strings with equally split parts
        var newString = ""
        for string in strings {
            newString += "\(string)\n" //joining all the strings back with newline
        }
       textView.text = String(newString.dropLast(2)) //dropping the new line sequence at the end
    }
}

You will need this extension to split String in equal parts for above code to work though:

extension String {
    func components(withMaxLength length: Int) -> [String] {
        return stride(from: 0, to: self.count, by: length).map {
            let start = self.index(self.startIndex, offsetBy: $0)
            let end = self.index(start, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
            return String(self[start..<end])
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1