You can see the following solutions to restrict the length of uitextfield on the Internet:CodeFor example, the maximum length is 20.
-(Bool) textfield :( uitextfield *) textfield shouldchangecharactersinrange :( nsange) range replacementstring :( nsstring *) String
{
If (range. Location> = 20)
Return no;
Return yes;
}
This problem has been discovered through actual application.
If we keep entering the text, the text cannot be entered at location = 20.
The problem is that location = 20. When we place the optical punctuation in any position in the text (location <20), we can also enter the text,
Therefore, we cannot limit the length of text to 20.
So I thought of a solution to limit the length of text content.
-(Bool) textfield :( uitextfield *) textfield shouldchangecharactersinrange :( nsange) range replacementstring :( nsstring *) String
{
Nsstring * textstring = textfield. text;
Nsuinteger length = [textstring length];
If (length> = 20)
Return no;
Return yes;
}
It seems that the length limit is implemented. Yes, it does, but there is a new problem, that is, when we enter 20 characters, we want to use the "delete" button on the keyboard
Deleting a single character also cannot delete any or already entered characters. I believe everyone understands the reason.
Currently, the solution I found is to make a judgment. After experiment, we found that the range is used to input characters. in general, the length is 0, and when you click the "delete" button, range. the value of length is 1.
The reason why I use it is usually 0 is because I tried it. I still don't know if there are other characters that lead to range. Length = 1.
So far the solution is like this
-(Bool) textfield :( uitextfield *) textfield shouldchangecharactersinrange :( nsange) range replacementstring :( nsstring *) String
{
Nsstring * textstring = textfield. text;
Nsuinteger length = [textstring length];
Bool bchange = yes;
If (length> = 20)
Bchange = no;
If (range. Length = 1 ){
Bchange = yes;
}
Return bchange;
}
I wonder if you have a better solution to limit the length of text input.