Question

I know it may seem very simple and has been asked many times but i can't get it to work .I want to add two buttons to my toolbar. One on the right side and the other one on the left. Here is the code but the flexible one which is supposed to show up on the right side doesn't appear at all. Here is the code:

toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
NSMutableArray *items = [[NSMutableArray alloc] init];

[items addObject:[[UIBarButtonItem alloc] initWithTitle:@"next" style:UIBarButtonItemStylePlain target:self action:@selector(nextResult:)]];

UIBarButtonItem *done=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:@selector(showSearch:)];
[done setImage:[UIImage imageNamed:@"cancel"]];
[items addObject:done];

[toolbar setItems:items animated:NO];
Was it helpful?

Solution

You need to use UIBarButtonSystemItemFlexibleSpace instead of UIBarButtonSystemItemFixedSpace

Code:

toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
NSMutableArray *items = [[NSMutableArray alloc] init];

[items addObject:[[UIBarButtonItem alloc] initWithTitle:@"next" style:UIBarButtonItemStylePlain target:self action:@selector(nextResult:)]];

UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:space];

[items addObject:[[UIBarButtonItem alloc] initWithTitle:@"cancel" style:UIBarButtonItemStylePlain target:self action:@selector(showSearch:)]];

[toolbar setItems:items animated:NO];

Reference : UIBarButtonItem Class Reference

OTHER TIPS

The item with the system item UIBarButtonSystemItemFixedSpace is a space, not button object. Therefore it does show up. It's just no button.

Change your code to

toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
NSMutableArray *items = [[NSMutableArray alloc] init];

[items addObject:[[UIBarButtonItem alloc] initWithTitle:@"next" style:UIBarButtonItemStylePlain target:self action:@selector(nextResult:)]];

UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:space];

[items addObject:[[UIBarButtonItem alloc] initWithTitle:@"cancel" style:UIBarButtonItemStylePlain target:self action:@selector(showSearch:)]];

[toolbar setItems:items animated:NO];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top