Reputation: 379
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
Reputation: 56059
A few observations:
...ShouldReturn
method. 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. [textField resign...]
instead of [sizeField resign...]
. At the least you should assert(textField == sizeField)
. Upvotes: 0
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