简体   繁体   中英

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
    }
}

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
    }

You can use something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM