Tuesday, March 1, 2011

Code Snippet: Character Counter

Many of us had a need to display an editable UITextView/UITextField in which only certain number of characters could be entered. It could be assumed something similar to Twitter clients as maximum length of any tweet cannot exceed by 140 characters limit. Today, we will implement this functionality in our application.

Step 1:
Let's define a UITextField where user will enter the text and a UITextView where the remaining characters will be displayed. Declare the following in your controller.h file
@interface RemainingCharacterViewController : UIViewController {
IBOutlet UITextView * remainingTextView;
}

@property (nonatomic, retain) IBOutlet UITextView * remainingTextView;

-(void)textFieldDidUpdate:(id)sender;


The above code is pretty straight forward. We first declare an IBOutlet for the UITextView that we will be updating. It will be used to show our characters remaining. Next, we declare an IBAction that will be called every time the user types a character in the UITextField. Now that our properties and actions have been set up, it’s time to create our interface. We won't need to declare the IBOutlet for UITextField which user will be editing as we could identify it by the (id)sender parameter.

Step 2:
Open up the Interface Builder and add a UITextView and connect the remainingTextView outlet to this element. Next, you will need to connect the textFieldDidUpdate IBOutlet to the Editing Changed action of the UITextField. Thus, whenever the text inside this textField is changed, it will fire the textFieldDidUpdate method.

Step 3:
textFieldDidUpdate is the method where we will put up all our code. Open the viewController.m file and add the following code;
@synthesize remainingTextView;

-(IBAction) textFieldDidUpdate:(id)sender {
UITextField * textField = (UITextField *) sender;
int maxChars = 140;
int charsLeft = maxChars - [textField.text length];

if(charsLeft == 0) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"No more characters"
message:[NSString stringWithFormat:@"You have reached the character limit of %d.",maxChars]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}

remainingTextView.text = [NSString stringWithFormat:@"%d characters remaining.",charsLeft];
}

- (void)viewDidUnload {
remainingTextView = nil;
}

- (void)dealloc {
[super dealloc];
[remainingTextView release];
}


First, we keep the maximum character limit to be 140 characters. Then we find the difference between this max. character limit and the characters entered in the textField. If this difference is 0 then we have reached our maximum limit, hence notify the user with a pretty alert message.
Now you are all done with the implementation of character counter.