fisher
fisher

Reputation: 1296

Max 4 lines AND a total of 140 characters in UITextView

I am using shouldChangeTextIn on the UITextView and I am able to limit the TextView to either a maximum of 4 lines OR a maximum of 140 characters using the following code in shouldChangeTextIn:

Max 4 lines:

    let existingLines = textView.text.components(separatedBy: CharacterSet.newlines)
    let newLines = text.components(separatedBy: CharacterSet.newlines)
    let linesAfterChange = existingLines.count + newLines.count - 1

    return linesAfterChange <= textView.textContainer.maximumNumberOfLines

Max 140 characters:

    let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)

    return newText.utf16.count < 140

However, I want to combine these two so it checks for both and I am not able to figure it out. Can anyone guide me in the right direction?

Best regards, Erik

Upvotes: 0

Views: 257

Answers (2)

Rakesha Shastri
Rakesha Shastri

Reputation: 11243

You should store the bool values instead of returning it and combine them with an && and return it.

let existingLines = textView.text.components(separatedBy: CharacterSet.newlines)
let newLines = text.components(separatedBy: CharacterSet.newlines)
let linesAfterChange = existingLines.count + newLines.count - 1
let linesCheck = linesAfterChange <= textView.textContainer.maximumNumberOfLines

let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
let characterCountCheck = newText.utf16.count < 140

return linesCheck && characterCountCheck

Sidenote: Avoid using NSString in Swift. You can do the same thing with String.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if let textViewString = textView.text, let range = Range(range, in: textViewString) {
        let newString = textViewString.replacingCharacters(in: range, with: text)
    }
    return condition
}

Upvotes: 2

aleixrr
aleixrr

Reputation: 489

Combine the boolean values with && (and operator) and return the result

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

        let existingLines = textView.text.components(separatedBy: CharacterSet.newlines)
        let newLines = text.components(separatedBy: CharacterSet.newlines)
        let linesAfterChange = existingLines.count + newLines.count - 1

        let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)

        return linesAfterChange <= textView.textContainer.maximumNumberOfLines && newText.utf16.count < 140
    }

Upvotes: 0

Related Questions