How to make color for UIToolbar the same as keyboard

892 Views Asked by At

I have issue with UIToolbar background color above the keyboard, here the picture: not expected background color on UIToolbar. I expected to see the same color as keyboard background, what I'm doing wrong?

I have this code:

UIToolbar* toolbar = [[UIToolbar alloc] init];
[toolbar sizeToFit];
UIBarButtonItem *spaceBarButton = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                  target:nil action:nil]; // to make close button on right side
UIBarButtonItem *closeBarButton = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemClose
                                  target:self action:@selector(endEditing:)];
toolbar.items = @[spaceBarButton, closeBarButton];
textField.inputAccessoryView = toolbar;
1

There are 1 best solutions below

0
Lauva On

So It seems I found solution its kinda hack, but still working.

UIInputView on init have inputViewStyle which mimics the keyboard background. If use UIInputView as parent view for UIToolbar with a clear background color, we will be good. Or use UIInputView itself, and add buttons on it, and apply it on inputAccessoryView without UIToolbar.

It depends on your content and future needs.

Example of keyboard what will shows: toolbar with right color implemented

My example with UIToolbar as subclass you can implement variant you want:

//add toolbar
UIToolbar* toolbar = [[UIToolbar alloc] init];
[toolbar sizeToFit];//get height for toolbar
CGFloat width = [UIScreen mainScreen].bounds.size.width;//set width for toolbar
CGRect frame = toolbar.frame;
frame.size.width = width;
toolbar.frame = frame;

//toolbar buttons setting
UIBarButtonItem *spaceBarButton = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                   target:nil action:nil]; // to make close button on right side
UIBarButtonItem *closeBarButton = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemClose
                                   target:textField action:@selector(endEditing:)];
toolbar.items = @[spaceBarButton, closeBarButton];

//make toolbar background clear color
[toolbar setBackgroundImage:[UIImage new]
         forToolbarPosition:UIToolbarPositionAny
                 barMetrics:UIBarMetricsDefault];
[toolbar setBackgroundColor:[UIColor clearColor]];

//creating UIInputView for using its background color
UIInputView *inputView = [[UIInputView alloc] initWithFrame:toolbar.bounds inputViewStyle:UIInputViewStyleKeyboard];
// UIInputViewStyleKeyboard - view mimics the keyboard background
[inputView addSubview:toolbar];
textField.inputAccessoryView = inputView;