Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering UIBarButtonItem in a UIToolbar and adding custom text

I need to add a button to the center of the ToolBar. I have done the adding the button to the toolbar part successfully. My problems are as follows;

1.) I need to center this barbutton. It should be in the center of the Tool Bar

2.) I need to have a text after the refresh button image is displayed.

toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0 , 320 , 60)];

    NSMutableArray* button = [[NSMutableArray alloc] initWithCapacity:1];

    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshButtonAction:)];

    [button addObject:barButton];

    [toolBar setItems:button animated:NO];

    [self.view addSubview:toolBar];
like image 552
sharon Avatar asked Dec 03 '22 00:12

sharon


2 Answers

1. Add flexible spacers before and after your bar button in the toolbar items array:

toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0 , 320 , 60)];

UIBarButtonItem *flexibleSpace =  [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshButtonAction:)];

NSArray *toolbarItems = [NSArray arrayWithObjects:flexibleSpace, barButton, flexibleSpace];

[toolBar setItems:toolbarItems animated:NO];

[self.view addSubview:toolBar];

Configuring toolbars is much easier to do in Interface Builder. If your view controller is inside a UINavigationController stack, you can still use IB to create an outlet collection of UIBarButtonItems and set self.toolbarItems in -viewDidLoad.

2. To get custom content in a toolbar you can create a bar button item with a custom view:

UIView *customView = <# anything, could be a UILabel #>;
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:customView];
like image 115
Ryder Mackay Avatar answered Dec 30 '22 09:12

Ryder Mackay


I know this can be done in IB, but I believe if you want to center a button, you will need to add a fixed or flexible space button on either side to keep your button in the middle. If you are going to do this with just code... try and sandwich your button between the 2 space buttons.

like image 43
Bill Burgess Avatar answered Dec 30 '22 09:12

Bill Burgess