Problem:
You want to add the button to the navigation bar
1. The navigation bar belongs to the uinavigationbar class. You can create it at any time and add it to any view.
2. To create a navigation button, you need to do the following:
Create a uibarbuttonitem instance.
Use the navigationitem attribute of the View Controller to add the button to the navigation bar of the View Controller ,. The navigationitem attribute allows us to interact with the navigation bar. This attribute has two attributes: rightbarbuttonitem and leftbarbuttonitem. Both attributes belong to the uibarbuttonitem class.
Code:
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(performAdd)];
We can create different system buttons: Use the initwithbarbuttonsystemitem: Target: Action: initialization method of the uibarbuttonitem class to complete this task.
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:selfaction:@selector(performAdd:)];
Among the best initialization methods in class uibarbuttonitem, one is initwithcustomview: method. This method can accept any view. This means that you can even add uiswitch as a button to the navigation bar. This does not seem like a problem, but it is worth a try.
UISwitch *simpleSwitch = [[UISwitch alloc]init]; simpleSwitch.on = YES; [simpleSwitch addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged]; self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:simpleSwitch];
Ui: Use uibarbuttonitem to add buttons to the navigation bar