限制中文输入长度

 let toBeString = textView.text
 let lang = textView.textInputMode?.primaryLanguage
 if lang == "zh-Hans" {
   let selectedRange = textView.markedTextRange
   if selectedRange == nil && (toBeString?.characters.count)! > 50{
          let index = toBeString?.index((toBeString?.startIndex)!, offsetBy: 50)
          textView.text = toBeString?.substring(to:index!)
    }
}else if (toBeString?.characters.count)! > 50  {
       let index = toBeString?.index((toBeString?.startIndex)!, offsetBy: 50)
       textView.text = toBeString?.substring(to:index!)
}

你可能感兴趣的:(限制中文输入长度)