Limit A Substring in UITextView With Swift

While integrating with Twitter in my current Swift app, I wanted to limit the number of lines in any given Tweet, aside from the limit of 140 characters. I didn’t see anything in the String class to do it directly, so instead I created a simple method to do it.

Here is the method.

As you can see, it simply takes in the String to evaluate, the substring for which you want to count occurrences, splits the String into an Array using the substring as separator, then determines the count. There will be one more token in the array than the number of separators so we subtract one from the number of elements to count the substring we are checking for.

To use this with a UITextView to limit the number of times a user can add a new line character, you use a UITextViewDelegate method like this to count “\n” occurrences.

In this case, we are limiting the number of new line characters to 4, so if the resulting text for a UITextView based on the user typing or cutting/pasting into the UITextView would result in either more than 140 characters, or more than 4 “\n” characters, the change is disallowed.

If you have another means of accomplishing the same thing, by all means leave a comment or send me an email.

Leave a Comment: