In this tutorial we will use Switch button to change the Color of Toolbar. The Switch is added through the Interface Builder and the Toolbar is created by coding, the project is based on View Based Application.
Final View will look like this:
My project name is SwitchChangesToolbarColor, Application is View Based and the coding is done in View Controller, first will declare the variable for the Toolbar, Switch and then will write the property for the variable which we created and after that will write the action for the Switch so that when click on Switch the color of the Toolbar changes and synthesize it in .m file to create getter and setter for the variable which we created in .h file (automatically).
Add this to ViewController.h file:
@property (nonatomic, retain) IBOutlet UISwitch *mswitch;
@property (nonatomic, retain) UIToolbar *mtool;
After synthesizing the variable in .m file will create the toolbar items which will be on the Toolbar and also will set the title for that, here am adding button and setting the title for that, the button style is UIBarButtonStyleDone and the variable is released. Then will add the Toolbar to the view and in that will create toolbar and also set the size and the frame. We can also set the style of the Toolbar, everything is done in viewDidLoad method and then will add Toolbar to the view.Now will write the method for the action which is declared in .h file, in that will change the color of the Toolbar using if else statement and also will write the action for the button which we created on the Toolbar. Finally release the variable which we created in .h file in dealloc method.
Add this to ViewController.m file:
@synthesize mswitch, mtool;
UIBarButtonItem *list = [[UIBarButtonItem alloc]initWithTitle:@" STOP "style:UIBarButtonItemStyleDone
NSArray *new = [NSArray arrayWithObjects:list, nil];
[self.mtool setItems:new animated:NO];
mtool = [UIToolbar new];
mtool.barStyle = UIBarStyleBlackTranslucent;
// mtool.barStyle = UIBarStyleDefault;
// mtool.barStyle = UIBarStyleBlackOpaque;
CGFloat toolbarHeight = [mtool frame].size.height;
CGRect mainViewBounds = self.view.bounds;
[mtool setFrame:CGRectMake(CGRectGetMinX(mainViewBounds), CGRectGetMinY(mainViewBounds) +
CGRectGetHeight(mainViewBounds) - (toolbarHeight * 1.0) + 2.0, CGRectGetWidth(mainViewBounds),toolbarHeight)];
UISwitch *swt = (UISwitch *)sender;
mtool.tintColor = [UIColor blackColor];
//toolbar.tintColor = nil; // back to first color of toolbar
mtool.tintColor = [UIColor orangeColor];
NSLog(@" Stop ");
Finally will connect all the variable which we created in .h will, the connection are done in Interface Builder
Make connections with Interface Builder:
Finally press Build And Go button
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.