我创建了一个 UIToolBar 作为 inputAccessoryView,其中包含一个下一个和上一个按钮,这些按钮将在我的视图控制器中的 textFields 中循环。
我根据此页面上的第三个 SO 答案在 UITextField 上创建了一个类别,该答案向指向下一个/上一个 textField 的 textField 添加了一个属性。
我可以让它向前和向后循环遍历文本字段,但只能循环一次,然后我的按钮被永久禁用。此外,当最后一个 textField 处于焦点时,我仍然需要再次点击下一个按钮(4 个点击 3 个 textFields)才能禁用下一个按钮 - 与上一个按钮相同,我必须点击一次后我'm 在第一个文本字段中。
// ViewController.h
@interface DetailViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate, UIPopoverControllerDelegate> {
__weak IBOutlet UITextField *valueField;
__weak IBOutlet UITextField *nameField;
__weak IBOutlet UITextField *serialNumberField;
}
@property (nonatomic, strong) UITextField *currentTextField;
- (IBAction)nextTextField:(id)sender;
- (IBAction)prevTextField:(id)sender;
// ViewController.m
- (void)viewDidLoad {
//...
nameField.delegate = self;
nameField.nextTextField = serialNumberField;
nameField.prevTextField = nil;
serialNumberField.delegate = self;
serialNumberField.nextTextField = valueField;
serialNumberField.prevTextField = nameField;
valueField.delegate = self;
valueField.prevTextField = serialNumberField;
valueField.nextTextField = nil;
//...
}
- (void)viewWillAppear:(BOOL)animated {
//UIToolBar for inputAccessoryView
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
UIBarButtonItem *nextField = [[UIBarButtonItem alloc] initWithTitle:@"\U00003009"
style:UIBarButtonItemStylePlain
target:self
action:@selector(nextTextField:)];
UIBarButtonItem *prevField = [[UIBarButtonItem alloc] initWithTitle:@"\U00003008"
style:UIBarButtonItemStylePlain
target:self
action:@selector(prevTextField:)];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(backgroundTapped:)];
NSArray *toolBarButtons = @[prevField, nextField, space, done];
toolBar.items = toolBarButtons;
nameField.inputAccessoryView = toolBar;
valueField.inputAccessoryView = toolBar;
serialNumberField.inputAccessoryView = toolBar;
}
- (IBAction)nextTextField:(id)sender {
UITextField *next = self.currentTextField.nextTextField;
if (!next) {
[sender setEnabled:NO];
} else {
[sender setEnabled:YES];
[next becomeFirstResponder];
}
}
- (IBAction)prevTextField:(id)sender {
UITextField *prev = self.currentTextField.prevTextField;
if (!prev) {
[sender setEnabled:NO];
} else {
[sender setEnabled:YES];
[prev becomeFirstResponder];
}
}