1

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
    }
}
manatee
  • 185
  • 1
  • 10

2 Answers2

3

Try this:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text
        let newLength = text.characters.count + string.characters.count - range.length
        return newLength <= 20
    }
chickenparm
  • 1,570
  • 1
  • 16
  • 36
  • Does not work, 1) when I break point on the function nothing happens, 2) I am using a text view not a text field – manatee Jun 06 '16 at 19:29
2

You can use something like this:

            if displayName.characters.count > 20 {
                displayName = (displayName as NSString).substringToIndex(20)
                displayName.appendContentsOf("...")
            }
Bhavuk Jain
  • 2,167
  • 1
  • 15
  • 23