manatee manatee - 6 months ago 11
iOS Question

How do I cut off the text view after 20 characters?

I am trying to limit the number of characters inside the text view to 20. After 20 it should instead have "...". The function is not firing and I am setting the delegate correctly.

Animal class

cell.pn.text = np[indexPath.row]
cell.pn.selectable = false
cell.pn.delegate = self


Extension of Animal class

extension Animal : UITextViewDelegate{
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
return textView.text.characters.count + (text.characters.count - range.length) <= 20
}
}

Answer

You can use something like this:

            if displayName.characters.count > 20 {
                displayName = (displayName as NSString).substringToIndex(20)
                displayName.appendContentsOf("...")
            }