Centering a UIBarButtonItem in a UIToolbar and Adding Custom Text

I need to add a button to the center of the ToolBar. I have successfully added a button to the toolbar. My problems are as follows:

1.) I need to focus this barbutka. It should be in the center of the toolbar.

2.) I need to have the text after the image of the refresh button 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]; 
+4
source share
2 answers

1. Add flexible delimiters before and after the panel button in the toolbar element 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 in Interface Builder. If your view controller is inside the UINavigationController stack, you can still use IB to create the UIBarButtonItem collection collection and set self.toolbarItems to -viewDidLoad .

2. To get custom content on the toolbar, you can create a panel element with a custom view:

 UIView *customView = <# anything, could be a UILabel #>; UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:customView]; 
+17
source

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

+1
source

Source: https://habr.com/ru/post/1388476/


All Articles