I have a UITextField and in that I should be able to type only integers (no text) and after that the integer values have to be passed to an NSMutableDictionary. Then from this dictionary I have to post to webserver.
            Asked
            
        
        
            Active
            
        
            Viewed 888 times
        
    2
            
            
         
    
    
        Moon Cat
        
- 2,029
- 3
- 20
- 25
 
    
    
        user3932799
        
- 57
- 7
- 
                    http://stackoverflow.com/questions/12944789/allow-only-numbers-for-uitextfield-input & http://stackoverflow.com/questions/10734959/uitextfield-should-accept-number-only-values – Mohit Aug 19 '14 at 10:18
- 
                    1how to pass the integer values to nsdictionary?? – user3932799 Aug 19 '14 at 10:32
4 Answers
3
            
            
        Change the keyboard type of UITextField to Number Pad so it only takes numbers:
[textField setKeyboardType:UIKeyboardTypeNumberPad];
You can also check whether the text entered is a number or not:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (string.length == 0 || [NSScanner scanInt:string]) {
        return YES;
    }
    return NO;
}
You can save the value in dictionary by using following code:
//if you want to save as number
[myDictionary setObject:[NSNumber numberWithInt:[textField.text intValue] forKey:@"YourKey"];
OR
//if you want to save as string
[myDictionary setObject:textField.text forKey:@"YourKey"];
 
    
    
        Salman Zaidi
        
- 9,342
- 12
- 44
- 61
3
            
            
        //Create a textfield
    txt = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 150, 50)];
    txt.placeholder = @"enter here";
    txt.borderStyle = UITextBorderStyleRoundedRect;
    txt.autocorrectionType = UITextAutocorrectionTypeNo;
    [txt setClearButtonMode:UITextFieldViewModeWhileEditing];
    [txt setKeyboardType:UIKeyboardTypeNumberPad];
    txt.delegate=self;
    [cell.contentView addSubview:txt];
You could check whether entered text is number or not:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [Height.text stringByReplacingCharactersInRange:range withString:string];
if([newString length] > 3)
{
    UIAlertView *obj_AlertView=[[UIAlertView alloc]initWithTitle:@""
                                                         message:@"Enter 3 digit only"
                                                        delegate:self
                                               cancelButtonTitle:@"OK"
                                               otherButtonTitles:nil];
    [obj_AlertView show];
}
    return !([newString length] > 3);
 }
now create a NSMutabledictionary in your button action to post
 -(IBAction)btnClicked:(id)sender
 {
  UIButton *button = (UIButton *)sender;
  button.tintColor=[UIColor redColor];
  NSLog(@"%@",button);
  NSMutableDictionary *datadict=[NSMutableDictionary dictionary];
now pass your textfield value to nsmutabledictionary to post
  if (txt.text !=NULL) {
    [datadict setValue:[NSNumber numberWithInt:[txt.text intValue]] forKey:@"txt"];
    //    [datadict setObject:[NSString stringWithFormat:@"%@",txt.text] forKey:@"txt"];   (if it is for NSdictionary)
} else {
[datadict setObject:[NSString stringWithFormat:@" "] forKey:@"txt"];
}
now post the value to web-server
   NSData* jsonData = [NSJSONSerialization dataWithJSONObject:datadict options:kNilOptions error:nil];
   NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  NSURL *someURLSetBefore =[NSURL URLWithString:@" your post web-server link here"];
  [request setURL:someURLSetBefore];
  [request setHTTPMethod:@"POST"];
  [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
  [request setHTTPBody:jsonData];
  NSError *error;
  NSURLResponse *response;
  NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  NSString * string1=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
   NSLog(@"%@",string1);
 
    
    
        Ganesh Kumar
        
- 708
- 6
- 25
2
            
            
        You can try something like this
1. Set the textField 'Keyboard Type' to Number Pad.
2.
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:[NSNumber numberWithInt:[textField.text intValue]] forKey:@"Key"];
Hope it helps.
 
    
    
        sabyasachi
        
- 74
- 3
0
            
            
        This one is the best way to do such things, make this following lines in NSString Category and check a validation as per your need.
-(NSString *)isTextFieldHasNumberOnly
{
   NSString *strMessage;
     NSString *enteredText=[self trimWhiteSpace];
    if ([enteredText length]==0) 
    {
        strMessage=@"Please enter number.";
        return strMessage;
    }
    NSString *numbEx = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
    NSRegularExpression *numbRegEx = [NSRegularExpression regularExpressionWithPattern:numbEx options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger numberOfMatches = [numbRegEx numberOfMatchesInString:enteredText options:0 range:NSMakeRange(0, [enteredText length])];
    if (numberOfMatches == 0)
        strMessage=@"Please enter valid number.";
    else
        strMessage=@"";
    return strMessage;
}
 
    
    
        Vijay Sanghavi
        
- 340
- 1
- 5
- 23