在我的应用程序中,navigationController 工具栏上有一个 UITextField。
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) NSArray *toolBarButtonItems;
@property (nonatomic,strong) UITextField *textField;
@property (nonatomic,strong) UITextField *textField2;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 60, 40)];
self.textField.delegate = self;
self.textField.borderStyle = UITextBorderStyleRoundedRect;
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.textField];
self.toolBarButtonItems = @[flexibleSpace,barButtonItem,flexibleSpace];
self.toolbarItems = self.toolBarButtonItems;
self.navigationController.toolbar.barTintColor = [UIColor blueColor];
[self.navigationController setToolbarHidden:NO animated:NO];
}
单击 textField 时,键盘打开,我创建了一个带有另一个 textField 的新 inputAccessoryView 工具栏。
-(UIToolbar *)addToolBar{
UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:self.navigationController.toolbar.frame];
toolbar.barTintColor = [UIColor darkGrayColor];
self.textField2 = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 60, 40)];
self.textField2.delegate = self;
self.textField2.borderStyle = UITextBorderStyleRoundedRect;
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.textField2];
[toolbar setItems:@[flexibleSpace,barButtonItem,flexibleSpace]];
return toolbar;
}
这个想法是将 firstResponder 更改为 inputAccessoryView 上的 textField ,这样我就可以看到我正在编辑的内容。我这样做的原因是我无法将导航工具栏向上滚动到键盘上方,并且我想查看正在编辑的文本。
-(void)textFieldDidBeginEditing:(UITextField *)textField{
textField.inputAccessoryView = [self addToolBar];
if(self.textField2.isFirstResponder != NO){
[self.textField2 becomeFirstResponder];
}
}
当我单击 navigationController 工具栏中的 textField 时,它似乎不起作用。新的 inputAccessoryView 工具栏显示在键盘上,但我无法编辑该字段,因为响应者似乎没有改变。返回键也不起作用。我必须按两次才能关闭键盘,当我这样做时,两个文本字段之间的文本不匹配。
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
self.textField.text = self.textField2.text;
return YES;
}