Skip to content

Instantly share code, notes, and snippets.

@kharmabum
Created February 14, 2014 19:19
Show Gist options
  • Save kharmabum/9007251 to your computer and use it in GitHub Desktop.
Save kharmabum/9007251 to your computer and use it in GitHub Desktop.
Delegate methods for tracking character count
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
int remainder = MAX_CHARACTER_COUNT - textField.text.length;
self.counterLabel.text = [NSString stringWithFormat:@"%d", remainder];
if (textField == self.activityNameTextField) {
self.counterLabel.yOrigin = self.activityNameContainerView.yOrigin;
[self closePlaceTableView];
} else {
self.counterLabel.yOrigin = self.placeContainerView.yOrigin;
[self.containerScrollView setContentOffset:CGPointMake(0, self.activityNameContainerView.yOrigin + self.activityNameContainerView.height) animated:YES];
if (!textField.text.length) [self openPlaceTableView];
}
}
- (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;
if (textField == self.placeNameTextField) {
if (!newLength)
[self openPlaceTableView];
else
[self closePlaceTableView];
}
if ((newLength <= MAX_CHARACTER_COUNT)|| returnKey) {
self.counterLabel.text = [NSString stringWithFormat:@"%d", MAX_CHARACTER_COUNT - newLength];
return YES;
} else {
return (newLength < textField.text.length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment