this article reprinted to http://blog.sina.com.cn/s/blog_9bf272cf01013lsd.html2011-10-05 16:48 533 people Read reviews (0)CollectionReport
1. How to implement the word limit for Uitextfield, uitextview and other input boxes
(1) First, be sure to let controller implement Uitextfielddelegate (for Uitextfield) or uitextviewdelegate (for Uitextview)
Then, set the delegate property of the input box to self.
(2) Then, we can use these two delegate functions to achieve our limit on the number of input words.
For Uitextfield is a function
-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) string;
Or
For Uitextview is a function
-(BOOL) TextView: (Uitextview *) TextView Shouldchangetextinrange: (nsrange) Range Replacementtext: (NSString *) text;
If you are allowed to continue typing, return yes, otherwise return No.
The code is as follows:
View Plain
- If the input exceeds the specified word count of 100, the input is no longer allowed
- -(BOOL) TextView: (Uitextview *) TextView Shouldchangetextinrange: (nsrange) Range Replacementtext: (NSString * ) text
- {
- if (range.location>=100)
- {
- return NO;
- }
- Else
- {
- return YES;
- }
- }
2. How to implement automatic calculation of the remaining words of the input box with input limit
For example, the above code, the input box can not exceed 100 words, how to calculate in real-time how many characters can be entered at the moment?
Uitextfield does not find a suitable function, it can also be used in the function
-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) string;
To achieve.
Code:
View Plain
- -(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) Range replacementstring :(NSString *) string
- {
- int remaintextnum_=100;
- Calculate how much text is left to enter
- if (range.location>=100)
- {
- remaintextnum_=0;
- return NO;
- }
- Else
- {
- NSString * NSTEXTCONTENT=STRING.TEXT;
- int existtextnum=[nstextcontent length];
- Remaintextnum_=100-existtextnum;
- return YES;
- }
- }
Uitextview In addition to the function
-(BOOL) TextView: (Uitextview *) TextView Shouldchangetextinrange: (nsrange) Range Replacementtext: (NSString *) text
is handled in a similar way as above, you can also
-(void) Textviewdidchange: (Uitextview *) processed in TextView.
The code is as follows:
View Plain
- //Calculate the number of words entered in this place
- - ( void ) Textviewdidchange: (uitextview *) textview
- {
- NSString * nstextcontent=textview.text;
- int existtextnum=[nstextcontent length];
- remaintextnum_=100 -existtextnum;
- }