Recent projects have a special need, is to limit the length of a textfield input text in a certain range (note, not the number of words), surf the internet a circle did not find similar article, here to write my method, mark:
1, add the Listener function to TextField:
Textfield.addtarget (Self, Action: "Textfieldtextdidchange:", forControlEvents:UIControlEvents.EditingChanged)
2, processing when the input content changes:
Func Textfieldtextdidchange (Textfield:uitextfield) { if let _ = textfield.text { if let Positionrange = TextField . markedtextrange { If let _ = Textfield.positionfromposition (Positionrange.start, offset:0) { //are using Pinyin, do not validate c4/>} else { //do not use Pinyin, validate self.checktextfieldlengthandmodify (TextField) } } else { //do not use pinyin, Verify self.checktextfieldlengthandmodify (TextField)}}}
3. Realizing the method of verifying the school
Check that the text of the input box is too long, and if it exceeds the length, do a truncated func checktextfieldlengthandmodify (Textfield:uitextfield) {if let text = textfield.text { If Self.checktextfiellength (TextField, Str:text) {//length normal, not processed} else {//out of length, start processing Self.view.makeToastCenter ("Input text too long") Let Len = text.length let txt = text as Nsstri ng If len > 0 {//is truncated to see if it is super long, if not too long, then continue to truncate until not too long//exp://apple Appl//app for var i = len-1; I >= 0; i--{Let txt_s = Txt.substringtoindex (i)//print ("txt_s: \ (txt_s)") If Self.checktextfiellength (TextField, str:txt_s) {//It's intercepted here TextField . Text = txt_s Break} else {//Continue interception} } } } }}
4, realize checktextfiellength, judge whether the text exceeds the input frame length
Func checktextfiellength (Textfield:uitextfield, str:nsstring), Bool {let rect = str.boundingrectwithsize ( Cgsizemake (CGFloat (maxfloat), CGFloat (Maxfloat)), options:. Useslinefragmentorigin, Attributes:textField.defaultTextAttributes, Context:nil) if Rect.width > Textfield.width { return false } else { return true }}
The length limit is limited by the length of the Uitextfield, and you can set the length of the limit according to your needs.
IOS (Swift) TextField limit the length of input text (not the number of words)