首先将视图场景的类更改为情节提要中的视图控制器。
首先使用标识符cell(在我的情况下)创建您的自定义单元格。
放置文本字段并设置标签101(在我的情况下)。
像这样继承 UITextFieldDelegate 和键盘工具栏值:
@interface TableViewController () <UITextFieldDelegate>
@property (nonatomic, strong) UITextField* textField1;
@property (nonatomic, strong) UITextField* textField2;
@property (nonatomic, strong) UITextField* lastTextField;
@property (nonatomic, copy) NSString* string1;
@property (nonatomic, copy) NSString* string2;
@property (nonatomic, strong) UIToolbar* keyboardToolbar;
@end
在viewDidLoad方法下面写代码:
- (void)viewDidLoad {
[super viewDidLoad];
//
self.keyboardToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
self.keyboardToolbar.barStyle = UIBarStyleBlackTranslucent;
self.keyboardToolbar.items = @[[[UIBarButtonItem alloc]initWithTitle:@"Cancel"
style:UIBarButtonItemStylePlain
target:self
action:@selector(cancelNumberPad:)],
[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil],
[[UIBarButtonItem alloc]initWithTitle:@"Apply" style:UIBarButtonItemStyleDone
target:self
action:@selector(doneWithNumberPad:)]];
[self.keyboardToolbar sizeToFit];
}
并实现这些方法:
-(void)cancelNumberPad:(id)sender {
[self.lastTextField resignFirstResponder];
}
-(void)doneWithNumberPad:(id)sender {
if(self.lastTextField == self.textField1) {
[self.textField2 becomeFirstResponder];
} else {
[self.lastTextField resignFirstResponder];
}
}
并为单元格编写初始化代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
UITextField* textField = [cell viewWithTag:101];
textField.inputAccessoryView = self.keyboardToolbar;
textField.delegate = self;
if(0 == indexPath.section && 0 == indexPath.row) {
self.textField1 = textField;
} else if(0 == indexPath.section && 1 == indexPath.row) {
self.textField2 = textField;
}
return cell;
}
现在我们必须实现 UITextFieldDelegate 方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField == self.textField1) {
self.string1 = [self.string1 stringByReplacingCharactersInRange:range withString:string];
} else if(textField == self.textField2) {
self.string2 = [self.string2 stringByReplacingCharactersInRange:range withString:string];
}
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
self.lastTextField = textField;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self doneWithNumberPad:nil];
return YES;
}