Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distribute buttons along length in UIToolbar?

In my application, I use some code, to dynamically add buttons with images to a UIToolbar:

[self.navigationController setToolbarHidden:NO];
UIImage *buttonImage1 = [UIImage imageNamed:@"1.png"];
UIImage *buttonImage2 = [UIImage imageNamed:@"2.png"];
UIImage *buttonImage3 = [UIImage imageNamed:@"3.png"];

UIBarButtonItem *toolButton1 = [[UIBarButtonItem alloc] initWithImage:buttonImage1 style:UIBarButtonItemStylePlain target:self action:@selector(btnSettingsClick:)];
UIBarButtonItem *toolButton2= [[UIBarButtonItem alloc] initWithImage:buttonImage2 style:UIBarButtonItemStylePlain target:self action:@selector(btnSettingsClick:)];
UIBarButtonItem *toolButton3 = [[UIBarButtonItem alloc] initWithImage:buttonImage3 style:UIBarButtonItemStylePlain target:self action:@selector(btnSettingsClick:)];

[self setToolbarItems:[NSArray arrayWithObjects:toolButton1, toolButton2, toolButton3, nil]];

But it is not working well:

screenshot

If I try to set another button style:

toolButton1.style = UIBarButtonSystemItemFlexibleSpace;
toolButton2.style = UIBarButtonSystemItemFlexibleSpace;
toolButton3.style = UIBarButtonSystemItemFlexibleSpace;

It also looks poor:

screenshot 2

How can I fix this?

like image 723
Andrey Avatar asked Apr 15 '13 18:04

Andrey


1 Answers

Add two additonal bar buttons that use the system style UIBarButtonSystemItemFlexibleSpace and place one between each of your existing buttons:

[self.navigationController setToolbarHidden:NO];
UIImage *buttonImage1 = [UIImage imageNamed:@"1"];
UIImage *buttonImage2 = [UIImage imageNamed:@"2"];
UIImage *buttonImage3 = [UIImage imageNamed:@"3"];

UIBarButtonItem *toolButton1 = [[UIBarButtonItem alloc] initWithImage:buttonImage1 style:UIBarButtonItemStylePlain target:self action:@selector(btnSettingsClick:)];
UIBarButtonItem *toolButton2= [[UIBarButtonItem alloc] initWithImage:buttonImage2 style:UIBarButtonItemStylePlain target:self action:@selector(btnSettingsClick:)];
UIBarButtonItem *toolButton3 = [[UIBarButtonItem alloc] initWithImage:buttonImage3 style:UIBarButtonItemStylePlain target:self action:@selector(btnSettingsClick:)];

[self setToolbarItems:[NSArray arrayWithObjects:
    toolButton1, 
    [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
    toolButton2, 
    [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
    toolButton3, 
    nil]];

It's weird to conceptualize, but the flexible space is actually a distinct object and not a style to apply to other objects.

like image 133
jszumski Avatar answered Sep 19 '22 15:09

jszumski