如何在 20 个字符后切断文本视图?

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

我正在尝试将文本视图中的字符数限制为 20 个。20 个之后应该改为“...”。该函数未触发,我正在正确设置委托。

动物class

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

动物的延伸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
    }
}

试试这个:

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
    }

你可以这样使用:

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