简体   繁体   中英

How do I only show UIToolBar when virtual keyboard is present

The toolbar gets shown even when using a hardware keyboard. This is the code I'm using to add the toolbar. I'm running this code in viewWillAppear.

 UIToolbar* numberToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    numberToolbar.barStyle = UIBarStyleDefault;
    numberToolbar.items = [NSArray  arrayWithObjects:
                           [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc]initWithTitle:NSLocalizedString(@"Close", @"Close") style:UIBarButtonItemStyleBordered target:self action:@selector(closeKeyboard)],
                           nil];
    [numberToolbar sizeToFit];
    self.mobileNumberTextField.inputAccessoryView = numberToolbar;

You can use NSNotificationCenter to identify if the keyboard shows or hides. Add the following lines on viewDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

and implement the methods to do your actions:

- (void)keyboardWillShow:(NSNotification*)notification
- (void)keyboardWillHide:(NSNotification*)notification

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM