There are times when there is a need to limit the number of words to be manipulated.
In the absence of a good set of methods, such as the TextView method is to use the proxy method
-(BOOL) TextView: (Uitextview *) TextView Shouldchangetextinrange: (nsrange) Range Replacementtext: (NSString *) text
{
if (textView.text.length >= number) {
Textview.text = [Textview.text substringtoindex:number];
return NO;
}else {
return YES;
}
}
But this kind of universal way absolutely forced to have the problem, the simple English is OK to say. But you're using pinyin and there's a problem. That is the back of the time you want to enter the discovery is not input. But according to the chain of words but can also directly point up.
Therefore, can not let the user even pinyin can not be hit out, you can only limit the number of words after the success of the input.
Therefore, it is possible to judge the word count whenever the text changes.
TextView has a proxy method -(void) Textviewdidchange: ( Uitextview *) TextView can listen to text content changes in real-time, but textfiled not, but @interface uitextfield:uicontrol < Uitextinput,nscoding>
So you can add monitoring
[Valuefield addTarget:self action:@selector(changetext :)forcontrolevents:uicontroleventeditingchanged];
So whether the agent method or its own implementation of the monitoring (TextView proxy implementation is similar), the content can be used to determine the number of words:
-(void)changetext:(uitextfield *) sender
{
bool Ischinese; // determines whether the current input method is Chinese
if ([[[[uitextinputmodecurrentinputmode] primarylanguage ]isequaltostring: @ "en-us"]) {
Ischinese =false;
}
Else
{
Ischinese =true;
}
nsinteger number = 0; //number of words to limit
if (sender.) tag = =30000) {
Number =5;
}Elseif (sender. Tag = =30001)
{
Number =one;
}
if (sender.) tag = =30000) {
//number bit
nsstring *str = [[Sendertext] stringbyreplacingoccurrencesofstring: @ "?" withstring : @ "" ];
if (Ischinese) { // Chinese Input Method
uitextrange *selectedrange = [Sender markedtextrange];
// get highlighted parts
uitextposition *position = [Sender positionfromposition: Selectedrange. Startoffset:0];
// No highlighted words, word count and limit for typed text
if (!position) {
NSLog (@ " kanji ");
if (str.length>=number +1) {
nsstring *strnew = [nsstringstringwithstring: str];
[SenderSetText: [strnew Substringtoindex: number]];
}
}
Else
{
NSLog (@ " input of the English has not been translated into the status of Chinese characters ");
}
}Else{
NSLog (@ "str=%@; this time length =%lu ", str, (unsignedlong) [str length]);
if ([str length]>=number +1) {
nsstring *strnew = [nsstringstringwithstring: str];
[SenderSetText: [strnew Substringtoindex: number]];
}
}
}
}
Uitextfield && Uitextview Restrictions limit word count practices