iOS textView限制输入字符数

2017-08-16  本文已影响19人  Oo晨晨oO

实现代理
然后实现下面方法:

func textViewDidChange(_ textView: UITextView) {
        if textView.text.characters.count > 0 {
            placeHolderLabel.alpha = 0
        } else {
            placeHolderLabel.alpha = 1
        }
        
        // 限制140个字符
        let TOTAL_NUM = 140
        if textView.text.characters.count > TOTAL_NUM {
            
            //获得已输出字数与正输入字母数
            let selectRange = textView.markedTextRange
            
            //获取高亮部分 - 如果有联想词则解包成功
            if let selectRange = selectRange {
                let position =  textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
            
            let textContent = textView.text
            let textNum = textContent?.characters.count
            
            //截取字符
            if textNum! > TOTAL_NUM {
                let index = textContent?.index((textContent?.startIndex)!, offsetBy: TOTAL_NUM)
                let str = textContent?.substring(to: index!)
                textView.text = str
            }
        }
        
    }
上一篇下一篇

猜你喜欢

热点阅读