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{
开发者_Python百科[sizeField resignFirstResponder];
return YES;
}
but the keyboard doesn't go away...
How do I validate the input and dismiss the keyboard?
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";
...
A few observations:
- As another poster suggested, make sure you set the keyboard's delegate correctly.
- 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. - If you want to dismiss on taps outside, you'll have to do that on your own.
- 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 calledsizeField
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. - 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 shouldassert(textField == sizeField)
.
精彩评论