Ui: Use uibarbuttonitem to add buttons to the navigation bar

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.