實(shí)現(xiàn)代理
然后實(shí)現(xiàn)下面方法:
func textViewDidChange(_ textView: UITextView) {
if textView.text.characters.count > 0 {
placeHolderLabel.alpha = 0
} else {
placeHolderLabel.alpha = 1
}
// 限制140個(gè)字符
let TOTAL_NUM = 140
if textView.text.characters.count > TOTAL_NUM {
//獲得已輸出字?jǐn)?shù)與正輸入字母數(shù)
let selectRange = textView.markedTextRange
//獲取高亮部分 - 如果有聯(lián)想詞則解包成功
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
}
}
}