iPhone – Aligning UIToolbar Items on Code Level

In Xcode, If you want to add items to the UIToolbar, you need to create an NSArray which stores all the items and put them to the UIToolbar using the setItems method.

If you want to align one items on the left and the another one on the right. you need to create a space item in between the two button in the array. That’s just like adding a Flexible Space Bar Button Item in Interface Builder.

// Initialize the bar items
leftButton = [[UIBarButtonItem alloc]
			initWithTitle:@"Left"
			style:UIBarButtonItemStyleBordered
			target:self
			action:@selector(leftButtonClicked:)];
rightButton = [[UIBarButtonItem alloc]
			initWithTitle:@"Right"
			style:UIBarButtonItemStyleBordered
			target:self
			action:@selector(rightButtonClicked:)];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc]
			initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
			target:nil
			action:nil];
				
// Add the items to the toolbar
[toolbar setItems:[NSArray arrayWithObjects:leftButton, flexibleSpace, rightButton, nil]];

// Add the toolbar view to the controller view
[self.view addSubview:toolbar];

 

Done =)

Reference: Stack Overflow – Aligning UIToolBar items?

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.