Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>UPDATE</strong></p> <p>I cannot delete this answer because it is the accepted one, but it was not correct. Here is the correct code, copied from TomA below:</p> <pre><code>#define MAXLENGTH 10 - (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSUInteger oldLength = [textField.text length]; NSUInteger replacementLength = [string length]; NSUInteger rangeLength = range.length; NSUInteger newLength = oldLength - rangeLength + replacementLength; BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound; return newLength &lt;= MAXLENGTH || returnKey; } </code></pre> <p><strong>ORIGINAL</strong></p> <p>I think you mean UITextField. If yes, then there is a simple way.</p> <ol> <li>Implement the <a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html" rel="noreferrer">UITextFieldDelegate</a> protocol</li> <li>Implement the <code>textField:shouldChangeCharactersInRange:replacementString:</code> method.</li> </ol> <p>That method gets called on every character tap or previous character replacement. in this method, you can do something like this:</p> <pre><code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ([textField.text length] &gt; MAXLENGTH) { textField.text = [textField.text substringToIndex:MAXLENGTH-1]; return NO; } return YES; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload