objective-cuikittoolbarinputaccessoryviewsizetofit

Alternative to sizeToFit to space items on toolbar assigned to keyboard inputAccessoryView?


I have created a toolbar and attached it as an inputAccessoryView to the keyboard following Paul Hudson's snippet here.

This is a legacy project with some Objective-C and I have converted Paul's code to Objective-C, however, when I use sizeToFit, it is not spacing out the icons across the top but instead left aligning them. How can I space these evenly from left to right so that four icons would be displayed evenly as in the example below.

This is my code. This code is called in ViewDidLoad:

-(void)addToolBarToKeyboardOfTextView: (UITextView*)view {
    UIImage *addimg = [UIImage imageNamed:@"addimage"];
    UIImage *addfile = [UIImage imageNamed:@"addfile"];
    UIImage *showtip = [UIImage imageNamed:@"showtip"];
    UIImage *close = [UIImage imageNamed:@"close"];
    
    UIToolbar *bar = [[UIToolbar alloc] init];
    UIBarButtonItem *addImage = [[UIBarButtonItem alloc] initWithImage:addimg style:UIBarButtonItemStylePlain target:self action:@selector(selectPhoto)];
 UIBarButtonItem *attachFile = [[UIBarButtonItem alloc] initWithImage:addfile style:UIBarButtonItemStylePlain target:self action:@selector(selectFile)];
    UIBarButtonItem *showTip = [[UIBarButtonItem alloc] initWithImage:showtip style:UIBarButtonItemStylePlain target:self action:@selector(showTip)];
     UIBarButtonItem *close = [[UIBarButtonItem alloc] initWithImage:close style:UIBarButtonItemStylePlain target:self action:@selector(closeSelf)];
   
    bar.items = @[addImage,addFile,showtip,close];
    [bar sizeToFit];
    view.inputAccessoryView = bar;
}

The code displays the inputAccessoryView but the icons are aligned left instead of spread across.

I want this:

enter image description here

I get this:

enter image description here

How can I get the icons to evenly space?


Solution

  • Put spacers between each button

    let spacerBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace ,