user959974
user959974

Reputation: 379

UITableViewCell with TextField and checks input

I am currently create a UITableViewCell with a UITextField in it. On click of the text field, I want to bring up a number keyboard that I created. And as I type, the textfield should check the input for me; on click of other place, the keypad should be dismissed.

Code:

UITableViewCell *sizeCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"sizeCell"];
sizeCell.textLabel.text = @"Size";
UITextField* sizeField = [[UITextField alloc] initWithFrame:CGRectMake(185, 10, 100, 28)];
sizeField.text = @"0";
sizeField.textAlignment = UITextAlignmentRight;
sizeField.textColor = [UIColor colorWithRed:50.0/255.0 green:79.0/255.0 blue:133.0/255.0 alpha:1.0f];
sizeField.backgroundColor = [UIColor clearColor];
sizeField.keyboardType = UIKeyboardTypeDecimalPad;

[sizeCell.contentView addSubview:sizeField]; 

rows = [[NSArray arrayWithObjects:switchCell, typeCell, sizeCell, nil] retain];

I tried to implement UITextFieldDelegate like:

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
   [sizeField resignFirstResponder];
   return YES;
}

but the keyboard doesn't go away...

How do I validate the input and dismiss the keyboard?

Upvotes: 0

Views: 1570

Answers (2)

Kevin
Kevin

Reputation: 56059

A few observations:

  1. As another poster suggested, make sure you set the keyboard's delegate correctly.
  2. If you want to dismiss the keyboard on keyboard return, make sure you have one on your custom keyboard and it's correctly set up to call the ...ShouldReturn method.
  3. If you want to dismiss on taps outside, you'll have to do that on your own.
  4. You are declaring sizeField inside the method where you are setting it up, then calling it from another method outside that scope. I assume you have a class variable called sizeField or you'd be getting a compiler error. However, declaring it again when you're setting it up like you do shadows the class variable declaration so it never gets set up. Incidentally, that's a memory leak.
  5. This shouldn't affect the actual running of the program if all else is correct (but it will if, e.g. 4 is the problem and not fixed), but I think it's better form to call [textField resign...] instead of [sizeField resign...]. At the least you should assert(textField == sizeField).

Upvotes: 0

Joe
Joe

Reputation: 57179

You never set the delegate on your textfield so that textFieldShouldReturn: gets called. Make sure your class conforms to UITextFieldDelegate and then do the following:

...
UITextField* sizeField = [[UITextField alloc] initWithFrame:CGRectMake(185, 10, 100, 28)];
sizeField.delegate = self; //This is important!
sizeField.text = @"0";
...

Upvotes: 3

Related Questions