Search code examples
iosobjective-cuitextfieldnstimernsdateformatter

How can user Enter time in a Text Field ios


I want user to enter time in a TextField. There are examples available to do it with a DatePicker but that consumes a lot of space in the app. When user taps on TextField he should enter hh:mm. Now there is a placeholder text but nothing to force user to enter in this format hh:mm

So how can I use hh:mm format in a TextField? OR in other words enter time in a text field.


Solution

  • Use UITextField's shouldChangeCharactersInRange:replacementString: delegate method to format hh:mm format text in textfield

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
      if ([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound)
      {
        // BasicAlert(@"", @"This field accepts only numeric entries.");
        return NO;
      }
      else
      {
        NSString *text = textField.text;
        NSInteger length = text.length;
        BOOL shouldReplace = YES;
    
        if (![string isEqualToString:@""])
        {
            switch (length)
            {
                case 2:
                    textField.text = [text stringByAppendingString:@":"];
                    break;
    
                default:
                    break;
            }
            if (length > 4)
                shouldReplace = NO;
        }
    
        return shouldReplace;
      }
      return YES;
    }