iOS Development Project-04 Add a navigation bar button

Source: Internet
Author: User
Tags uikit

iOS Development Project-04 Add a navigation bar button

One, set the navigation bar button

The effect of the required implementation:

Description: The picture is not the same in the default state and the highlighted state.

The picture of the button needs to be displayed when the default state and highlight state are set, the system provides the following method

Viewcontroller.navigationitem.leftbarbuttonitem=[uibarbuttonitem alloc]initwithimage:<# (UIImage *) #> style: <# (Uibarbuttonitemstyle) #> target:<# (ID) #> action:<# (SEL) #>

Here, we need to set up the picture in two states, obviously this method does not meet our needs. So we're in position. Uibarbuttonitem adds a category that expands a method to allow two images to be set in two states.

1//2//  UIBARBUTTONITEM+EXTENSION.M 3//  04-button on the Weibo navigation bar 4//5//  Created by Apple on 14-7-4.6//7//8  9 #import "Uibarbuttonitem+extension.h" @implementation Uibarbuttonitem (Extension) + (Uibarbuttonitem *) Itemwithimagename: (NSString *) ImageName highimagename: (NSString *) Highimagename target: (ID) Target action: (SEL) Action13 {//     custom UIVIEW15     UIButton *btn=[[uibutton alloc]init];16     //Set button background picture (default/Highlight)     [ BTN setbackgroundimage:[uiimage Imagewithname:imagename] forstate:uicontrolstatenormal];19     [btn Setbackgroundimage:[uiimage Imagewithname:highimagename] forstate:uicontrolstatehighlighted];20     // The size of the Set button is as large as the picture, using the uiimage classification of     btn.size=btn.currentbackgroundimage.size;23     [btn addtarget:target action : Action forcontrolevents:uicontroleventtouchupinside];24     return [[Uibarbuttonitem alloc] initwithcustomview:btn];26    }28 @end

Second, fallback and jump to the homepage

1. The effect required to achieve:

After the program starts, the first page interface is displayed:

Click the button in the left corner of the interface navigation bar to jump to one (notice the buttons on both sides of the navigation bar)

Click the "Jump to the" button to jump to the other (note the right button on the navigation bar)

Click "Jump to three" button to jump to three

Note: Click the Back button on the left side of the navigation bar (---) to return to the previous screen, click the button on the right side of the navigation bar (... ) can be returned to the corresponding homepage.

Click the button to the right of the navigation bar in three to return home

Message interface:

Click on the cell to jump to a new interface (note the button on the navigation bar)

Description: In the project has multiple sub-pages of the navigation bar, need to go back to the previous page and jump to the homepage of the pair of barbuttonitem, we know that the navigation bar button settings need to set the corresponding navigation controller to complete, to unify the navigation bar in many places to use the button.

2. Here are three ways to implement

(1) The more stupid way to do this is to implement the following method once for each corresponding page.

If the 100 pages need such a navigation bar, then you need to copy the same Code 100 copies to the corresponding page, is it necessary? This approach can actually be implemented, but it is always the same code that is too junk.

(2) extracting a parent class

The practice of extracting public code into the base controller (extracting the public parent class) is problematic, but it is not possible to do so.

The so-called problem: Inheriting Uitableviewcontroller cannot inherit the underlying parent class.

Inheritance does not guarantee that all controllers inherit the common parent class, so it is not possible to use inheritance, generally inherited from the system controller is good, do not have inheritance constraints.

Description: Controllers in iOS are rarely inherited because multiple controllers are available in iOS

(3) Intercept push operation

Through analysis, we can intercept the push operation by setting it directly in the custom navigation controller. When push, the stack to judge, as long as the current push is not the bottom of the controller, then the unified navigation bar set Leftbarbuttonitem and Rightbarbuttonitem, in their listening methods to complete the previous page and back to the home operation.

 1-(void) Pushviewcontroller: (Uiviewcontroller *) Viewcontroller animated: (BOOL) Animated 2 {3//If the current push is not a stack top controller,          So long hidden Tabbar toolbar 4 if (self.viewcontrollers.count>0) {5 Viewcontroller.hidesbottombarwhenpushed=yes; 6 7//Intercept push action, set the upper-left corner of the navigation bar and the upper-right button 8 Viewcontroller.navigationitem.leftbarbuttonitem=[uibarbuttonitem Itemwi thimagename:@ "Navigationbar_back" highimagename:@ "navigationbar_back_highlighted" target:self Action: @selector ( back)]; 9 Viewcontroller.navigationitem.rightbarbuttonitem=[uibarbuttonitem itemwithimagename:@ "Navigationbar_more" HighI magename:@ "navigationbar_more_highlighted" target:self Action: @selector (more)];10}12 [Super Pushviewco Ntroller:viewcontroller animated:yes];13}14-(void) Back16 {#warning Here is self, because self is the navigation controller currently in use [self pop viewcontrolleranimated:yes];19}20-(void) More22 {[Self poptorootviewcontrolleranimated:yes];24} 

If in a certain page, we do not need the system to set the navigation bar button, then you can directly on the corresponding page to the navigation bar Leftbarbuttonitem and Rightbarbuttonitem to reset, overwriting the system settings.

For example, the button on the right side of the navigation bar, the code is as follows:

1//Reset the buttons in the upper right corner of the navigation bar to override the system Unified Scenario 2-(void) ViewDidLoad3 {4     [super viewdidload];5     6     Self.navigationitem.rightbarbuttonitem=[[uibarbuttonitem alloc]initwithtitle:@ "can really set" style: Uibarbuttonitemstyledone target:self Action:nil];7}

Tip: The advantage of customizing the navigation controller is that you can intercept many operations.

3. Implementation of the third method

(1) Import the necessary picture resources

Description: Hard disk copy of the hard drive

(2) Create three new pages to demonstrate the effect

Set the code to jump after clicking the button:

1//2//  YYONEVIEWCONTROLLER.M 3//  04-button on the Weibo navigation bar 4//5//  Created by Apple on 14-7-4.6//7//8  9 #imp Ort "YYOneViewController.h" #import "YYTwoViewController.h" one @interface Yyoneviewcontroller ()-(ibaction) jump2two;14 @end16 @implementation YYOneViewController18 19//Click the button to jump to the second interface (ibaction) jump2two {     + Yytwoviewcontroller *two=[[yytwoviewcontroller alloc]init];22     [email protected] "the other";     Self.navigationcontroller pushviewcontroller:two animated:yes];24}25 @end

Third, the implementation of code

1.UIImage Classification, Expansion method:

Uiimage+extension.h file

1//2//  Uiimage+extension.h 3//   4//5//  Created by Apple on 14-7-3.6//7//8  9 #import <uikit/u Ikit.h>10 @interface UIImage (Extension) + (UIImage *) Imagewithname: (NSString *) name;13 @end

UIIMAGE+EXTENSION.M file

1//2//  UIIMAGE+EXTENSION.M 3//   4//5//  Created by Apple on 14-7-3.6//  7//8  9 #import "Uiima Ge+extension.h "Ten @implementation UIImage (Extension) + (UIImage *) Imagewithname: (NSString *) name13 {     UIImage *image = nil;15     if (iOS7) {//handling iOS7 nsstring *newname         = [name stringbyappendingstring:@ ' _os7 '];1 7         image = [UIImage imagenamed:newname];18     }19     if (image = = nil) {+         image = [UIImage imagenamed:name];22     }23     return image;24}25 @end

2.UIBarButtonItem Classification, Expansion method:

Uibarbuttonitem+extension.h file

1//  Uibarbuttonitem+extension.h 2//  04-button on the Weibo navigation bar 3//4//  Created by Apple on 14-7-4.5  6  7 #import <UIKit/UIKit.h> 8  9 @interface Uibarbuttonitem (Extension) + (Uibarbuttonitem *) Itemwithimagename: ( NSString *) ImageName highimagename: (NSString *) Highimagename target: (ID) Target action: (SEL) action;11 @end

UIBARBUTTONITEM+EXTENSION.M file

1//2//  UIBARBUTTONITEM+EXTENSION.M 3//  04-button on the Weibo navigation bar 4//5//6  7 #import "Uibarbuttonitem+extension.h" 8< C3/>9 @implementation Uibarbuttonitem (Extension) + (Uibarbuttonitem *) Itemwithimagename: (NSString *) ImageName Highimagename: (NSString *) Highimagename target: (ID) Target action: (SEL) action11 {     //Custom UIView13     UIButton * Btn=[[uibutton alloc]init];14     //Set button background picture (default/Highlight)     [btn setbackgroundimage:[uiimage Imagewithname : ImageName] forstate:uicontrolstatenormal];17     [btn setbackgroundimage:[uiimage Imagewithname:highimagename] forstate:uicontrolstatehighlighted];18     //Set the size of the button is as large as the picture, using the UIImage classification of the     btn.size= Btn.currentbackgroundimage.size;21     [btn addtarget:target action:action forcontrolevents: uicontroleventtouchupinside];22     [[Uibarbuttonitem alloc]initwithcustomview:btn];24    25} @end

3..UIView Classification, Expansion method:

Uiview+extension.h file

1//2//  Uiview+extension.h 3//4  5 #import <UIKit/UIKit.h> 6  7 @interface UIView (Extension) 8 @prope Rty (nonatomic, assign) CGFloat x; 9 @property (nonatomic, assign) cgfloat y;10 @property (nonatomic, assign) cgfloat width;11 @property (nonatomic, assign) CGFloat height;12 @property (nonatomic, assign) cgsize size;13 @end

UIVIEW+EXTENSION.M file

 1//2//UIVIEW+EXTENSION.M 3//4 5 #import "Uiview+extension.h" 6 7 @implementation UIView (Extension) 8 9-(void ) SetX: (cgfloat) x10 {CGRect frame = self.frame;12 frame.origin.x = x;13 Self.frame = frame;14}15-(CGFL Oat) x17 {return self.frame.origin.x;19}20-(void) Sety: (cgfloat) Y22 {cgrect frame = self.frame;24 fr AME.ORIGIN.Y = y;25 Self.frame = frame;26}27-(cgfloat) y29 {return self.frame.origin.y;31}32-(void) s Etwidth: (cgfloat) width34 {cgrect frame = self.frame;36 Frame.size.width = width;37 Self.frame = frame;38}3 9-(CGFloat) width41 {self.frame.size.width;43}44-(void) SetHeight: (cgfloat) height46 {CGRect frame = self.frame;48 Frame.size.height = height;49 Self.frame = frame;50}51-(cgfloat) height53 {retur  n self.frame.size.height;55}56-(void) SetSize: (cgsize) size58 {i//self.width = size.width;60//Self.height = size.height;61 CgreCT frame = self.frame;62 Frame.size = size;63 Self.frame = frame;64}65-(cgsize) size67 {self.fr ame.size;69}70 @end

4. Core code, intercept push operation

YYUINAVIGATIONVIEWCONTROLLER.M file

 1//2//YYUINAVIGATIONVIEWCONTROLLER.M 3//4 5 #import "YYNavigationViewController.h" 6 7 @interface Yynavigationvi Ewcontroller () 8 9 @end10 @implementation YYNavigationViewController12-(void) VIEWDIDLOAD14 {[Super Viewdi Dload];16}17-(void) Pushviewcontroller: (Uiviewcontroller *) Viewcontroller animated: (BOOL) ANIMATED19 {20//if Pus now H is not a stack top controller, so long hidden tabbar toolbar if (self.viewcontrollers.count>0) {Viewcontroller.hidesbottombarwhenpushed=ye S;23 24//Intercept push action, set the upper-left corner of the navigation bar and the upper-right corner button Viewcontroller.navigationitem.leftbarbuttonitem=[uibarbuttoni TEM itemwithimagename:@ "Navigationbar_back" highimagename:@ "navigationbar_back_highlighted" Target:self action:@ Selector (back)];26 viewcontroller.navigationitem.rightbarbuttonitem=[uibarbuttonitem itemwithimagename:@ "     Navigationbar_more "highimagename:@" navigationbar_more_highlighted "target:self Action: @selector (more)];27 28 }29 [Super Pushviewcontroller:viewcontroLler animated:yes];30}31-(void) back33 {#warning Here is self, because self is the navigation controller currently in use [self Popviewcontrolleranima ted:yes];36}37-(void) More39 {[Self poptorootviewcontrolleranimated:yes];41}42 @end

5. Home controller code, set the homepage of the navigation bar button

YYHOMETABLEVIEWCONTROLLER.M file

 1//2//YYHOMETABLEVIEWCONTROLLER.M 3//4 5 #import "YYHomeTableViewController.h" 6 #import "YYOneViewController.h" 7 8 @interface Yyhometableviewcontroller () 9 @end11 @implementation YYHomeTableViewController13-(ID) initwiths Tyle: (Uitableviewstyle) style15 {self = "super initwithstyle:style];17 if (self) {//Custom Initializ     Ation19}20 return self;21}22-(void) viewDidLoad24 {+ [super viewdidload];26 27//Set navigation bar button 28 Self.navigationitem.leftbarbuttonitem=[uibarbuttonitem itemwithimagename:@ "Navigationbar_friendsearch"     highimagename:@ "navigationbar_friendsearch_highlighted" target:self Action: @selector (Friendsearch)];29 Self.navigationitem.rightbarbuttonitem=[uibarbuttonitem itemwithimagename:@ "Navigationbar_pop" highImageName:@ " navigationbar_pop_highlighted "target:self Action: @selector (POP)];30}31-(void) POP32 {yylog (@"---pop---"); 34}35- (void) Friendsearch36 {37//jump to one of this sub-controller interface YyoneviewcontrolLer *one=[[yyoneviewcontroller alloc]init];39 [email protected] "one"; 40//Get current Controller [SELF.NAVIGATIONCONTR Oller pushviewcontroller:one animated:yes];42}44 #pragma mark-table View data source46-(Nsinteger) TableView :(UITableView *) TableView numberofrowsinsection: (Nsinteger) section47 {return 20;49}50 Wuyi-(UITableViewCell *) tabl     Eview: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexPath52 {static nsstring *id = @ "cell"; 54 UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:id];55 if (!cell) {cells = [uitable] Viewcell alloc] Initwithstyle:uitableviewcellstylesubtitle reuseidentifier:id];57}58 cell.textLabel.text = [NSStr ing stringwithformat:@ "%d----home test data", indexpath.row];59 return cell;60}61-(void) TableView: (UITableView *) Tablevi EW Didselectrowatindexpath: (Nsindexpath *) indexPath63 {64//when clicking on the cell, skip to the next interface, Uiviewcontroller *NEWVC = [UIView Controller alloc] init];NewVc.view.backgroundColor = [Uicolor redcolor];67 newvc.title = @ "new controller"; [Self.navigationcontroller push] VIEWCONTROLLER:NEWVC animated:yes];69}70 @end

6.Two Code

YYTWOVIEWCONTROLLER.M file

1//2//  YYTWOVIEWCONTROLLER.M 3//4  5 #import "YYTwoViewController.h" 6 #import "YYThreeViewController.h" 7
   
    8 @interface Yytwoviewcontroller () 9-(ibaction) jump2three;10 @end12 @implementation YYTwoViewController14 15 16 Reset the button in the upper-right corner of the navigation bar to override the system unified scheme-(void) viewDidLoad18 {     [super viewdidload];20]     Self.navigationitem.rightbarbuttonitem=[[uibarbuttonitem alloc]initwithtitle:@ "can really set" style: Uibarbuttonitemstyledone target:self action:nil];22}23//Click the button to jump to the third interface-(ibaction) Jump2three {     Yythreeviewcontroller *three=[[yythreeviewcontroller alloc]init];26     [email protected] "three";     Self.navigationcontroller pushviewcontroller:three animated:yes];28}29 @end
   

7. pch file for Project

1//2//  Prefix Header 3//4//Contents of this file is implicitly included at the beginning of every  sour CE file. 5//6  7 #import <Availability.h> 8  9 #ifndef __iphone_5_010 #warning "This project uses features only avail Able in IOS SDK 5.0 and later. " #endif12 #ifdef __objc__14     #import <uikit/uikit.h>15     #import <foundation/foundation.h>16     #import "Uiimage+extension.h"     #import "Uibarbuttonitem+extension.h"     #import "Uiview+extension.h" #ifdef Debug/debug status, open log function #define YYLOG (...) NSLog (__va_args__) #else//release status, turn off log function at #define YYLOG (...) #endif25 26 27//Random color #define Yyrandomcolor [Uicolor colorwithred:arc4random_uniform (/255.0 green:arc4random_) Uniform (/255.0 blue:arc4random_uniform)/255.0 alpha:1.0]29 30//Is iOS731 #define IOS7 ([[Uidevice] Currentdevice].systemversion Doublevalue] >= 7.0) #endif

Iv. Additional Information

(1) Mac--->ios

If you open a previous project, the project is clearly an iOS project, but it appears as a Mac project:

The adjustment measures are as follows:

Locate the storage path and right-click to display the package contents

The files in the package appear as follows:

Where Xcuserdata is equivalent to a cache, after deleting the file, reopen the project.

(2) Print on log

In a PCH file, conditional compilation

1 #ifdef Debug/debug status, open log function 2 #define YYLOG (...) NSLog (__va_args__) 3 #else//Publish status, turn off log function 4 #define YYLOG (...) 5 #endif

When you need to use NSLog printing, you can use the Yylog directly.

(3) Set the navigation bar to be black opaque

Tags: iOS development, Project article Green channel: Good text to the top of my collection This article contact me the top of the text
Follow-11
Fans-625 + plus attention00(Please comment on the article) «Previous: iOS Development project-03 Add navigation Controller
» Next: iOS development project-05 Theme settings

Posted on 2014-07-04 23:37 text top reading (4983) Comments (2) Edit Collection

Reviews # F2015-01-24 13:49 The snail that moved the bricks

Set button size for BTM in UIBARBUTTONITEM+EXTENSION.M error

Btn.size = btn.currentBackgroundImage.size;
"Property ' size ' isn't found on object of type ' UIButton"

Maybe you can use cgrect frame = btn.frame;
Frame.size = btn.currentBackgroundImage.size;
Btn.frame = frame;
Replace. Support (0) objection (0)Reply Reference

#2楼2015-01-26 11:10 The snail that moved the bricks

Hello, Bo Lord.
Block push, set the upper-left corner of the navigation bar and the upper-right button
The method in this way Xcode error said the choice of the Unknown class method Itemwithimagename,
In fact, I'm all the same. PCH Import header file, press COMMAND + left can jump past this method up, but just can't run compile, this is why AH?

iOS Development Project-04 Add a navigation bar button

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.